user217572
user217572

Reputation: 183

problem related to NSString

I have 1 NSString *abc = @"Hardik"; i have NSMutableArray *array; now i had written [array addobject:abc];

then i'm printing,NSLog(@"array = %@", array);

but i'm getting NULL why? I have declared NSMutableArray *array; in a.h file i had set @property(nonatomic,retain)NSMutableArray *array; @synthesize array;

and i have synthesize it but getting value NULL I'm not able to understand it?

Upvotes: 0

Views: 130

Answers (4)

TechZen
TechZen

Reputation: 64428

To trigger the synthesized accessor within a class itself, you must use self. If you don't, you access the attribute's address directly bypassing the accessor methods. You need:

NSString *abc = @"Hardik";
[self.array addobject:abc];
NSLog(@"array = %@", self.array);

The reason this is important is that the synthesized methods usually also initialize the property. The internals of the synthesize array method would look something like:

-(NSArray *) array{
    if (array!=nil) {
        return array;
    }
    array=[[NSMutableArray alloc] initWithCapacity:1];
    return array;
}

self.propertyName is really just shorthand for [self propertyName] and self.propertyName=someValue is just shorthand for [self setPropertyName:someValue].

Until you call self.array at least once, the array property is not initialized.

However, just to confuse things, once you have called self.array once it is initialized so you can just call array directly. So...

[self.array addObject:abc];
NSLog(@"array = %@", array);

...works while the converse would return just an empty array.

So the rules are:

  1. Within a class implementation (including subclasses), calling just propertyName gives you the address of the property but does not call the getter/setter accessor methods.
  2. Within a class implementation (including subclasses), using self.propertyName calls the getter/setter accessor methods but does not access attribute directly.
  3. From outside the class implementation e.g. myClass.propertyName calls the getter/setter accessor methods.

Upvotes: 0

mmccomb
mmccomb

Reputation: 13807

It sounds like your NSMutableArray* array property may not have been initialised?

Can you post your class init method?

Upvotes: 0

Stephen Darlington
Stephen Darlington

Reputation: 52565

You also need to initialise your array:

array = [[NSMutableArray alloc] initWithCapacity:10];

This is pretty fundamental stuff. Have you read the "Learning Objective C Primer" yet?

Upvotes: 4

Alex
Alex

Reputation: 26859

It sounds like you haven't actually allocated array. Generally, you would do this in your initializer. (Don't forget to add a release to your dealloc method, too.) @synthesize creates the getter and setter, but you still have to handle allocating/deallocating the object yourself.

Upvotes: 3

Related Questions