Friday, June 21, 2013

NSMutableSet addObject example in Objective C (iOS).


NSMutableSet addObject

Adds a given object to the set, if it is not already a member.

- (void)addObject:(id)object

Parameters of [NSMutableSet addObject]
object
The object to add to the set.

NSMutableSet addObject example.
- (void)applicationDidFinishLaunching:(UIApplication *)application {   
    NSSet *s=[NSSet setWithObject:@"setWithObject"];
    NSMutableSet *m=[NSMutableSet setWithCapacity:1];
    [m addObject:@"Added String"];
    NSMutableSet *n = [[NSMutableSet alloc] initWithCapacity:1];
    [self showSuperClasses:s];
    [self showSuperClasses:m];
    [self showSuperClasses:n];
    [self showSuperClasses:@"Steve"];  
}

- (void) showSuperClasses:(id) anObject{
    Class cl = [anObject class];
    NSString *classDescription = [cl description];
    while ([cl superclass])
    {
        cl = [cl superclass];
        classDescription = [classDescription stringByAppendingFormat:@":%@", [cl description]];
    }
    NSLog(@"%@ classes=%@",[anObject class], classDescription);
}

Example of [NSMutableSet addObject].
At some point before you use the set, you need to create a new NSMutableSet.

To make it easy, you can use something like the following to automatically allocate a new mutable set when you ask to use it for the first time.

- (NSMutableSet *)NHPList {
    if (NHPList == nil) {
        NHPList = [[NSMutableSet alloc] init];
    }
    return NHPList;
}
You would also have to release the memory, usually in your viewDidUnload method by setting NHPList to nil.

If this is the only place that you set the data, you could also just change this line:

[NHPList addObject:[sub name]];
to:

if (self.NHPList == nil) {
    self.NHPList = [[NSMutableSet alloc] init];
}
[self.NHPList addObject:[sub name]];

NSMutableSet addObject example.
+ (NSSet *)variablesInExpression:(id)anExpression
{
NSMutableSet *setOfVariables = [[NSMutableSet alloc] init];
for (NSString *str in anExpression) {
    if ([str hasPrefix:VARIABLE_PREFIX]) {
        [setOfVariables addObject:str];
    }
}
[setOfVariables autorelease];
return setOfVariables;
}

End of NSMutableSet addObject example article.