codescracker


objective c

Objective-C Composite Object



« Previous Tutorial Next Tutorial »


You are free to create a subclass within a class cluster in Objective-C, that defines a class, that embeds within it an object, and these class objects are called as composite objects.

Class clusters are a design pattern that Foundation framework makes extensive use of. Class clusters in Objective-C, groups a number of private concrete subclasses under a public abstract superclass. By embedding private cluster object in an object of your own design, then you are creating composite object in Objective-C.

Objective-C Composite Object Example

Here is an example program, demonstrates the concept of composite object in Objective-C:

/* Objective-C Composite Object - Example Program */
		
#import <Foundation/Foundation.h>
@interface VALIDATE_ARRAY : NSMutableArray
{
	NSMutableArray *embedded_array;
}
+ VALIDATE_ARRAY;
- init;
- (unsigned)count;
- objectAtIndex:(unsigned)index;
- (void)addObject:object;
- (void)replaceObjectAtIndex:(unsigned)index withObject:object;
- (void)removeLastObject;
- (void)insertObject:object atIndex:(unsigned)index;
- (void)removeObjectAtIndex:(unsigned)index;
@end
@implementation VALIDATE_ARRAY
- init
{
	self = [super init];
	if (self)
	{
		embedded_array = [[NSMutableArray allocWithZone:[self zone]] init];
	}
	return self;
}
+ VALIDATE_ARRAY
{
	return [[self alloc] init] ;
}
- (unsigned)count
{
	return [embedded_array count];
}
- objectAtIndex:(unsigned)index
{
	return [embedded_array objectAtIndex:index];
}
- (void)addObject:(id)object
{
	if(object != nil)
	{
		[embedded_array addObject:object];
   }
}
- (void)replaceObjectAtIndex:(unsigned)index withObject:(id)object;
{
	if(index <[embedded_array count] && object != nil)
	{
		[embedded_array replaceObjectAtIndex:index withObject:object];
	}
}
- (void)removeLastObject;
{
	if([embedded_array count] > 0)
	{
		[embedded_array removeLastObject];
	}
}
- (void)insertObject:(id)object atIndex:(unsigned)index;
{
	if(object != nil)
	{
		[embedded_array insertObject:object atIndex:index];
	}
}
- (void)removeObjectAtIndex:(unsigned)index;
{
	if(index <[embedded_array count])
	{
		[embedded_array removeObjectAtIndex:index];
	}
}
@end

int main()
{
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	VALIDATE_ARRAY *validating_array = [VALIDATE_ARRAY validating_array];
	[validating_array addObject:@"Object1"];
	[validating_array addObject:@"Object2"];
	[validating_array addObject:[NSNull null]];
	[validating_array removeObjectAtIndex:2];
	NSString *aString = [validating_array objectAtIndex:1];
	NSLog(@"The value at Index 1 is %@",aString);
	[pool drain];
	
	return 0;
}

Now when we compile and run the above program, then we will get the following output:

2015-10-03 22:03:54.294 demo[6247] The value at Index 1 is Object2

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test