yosh
yosh

Reputation: 3305

iPhone Obj-C - Retrieve custom object from NSMutableArray

Having:

@interface MyClass : NSObject {
    NSString *name; // retained and synthesized
    NSString *address; // retained and synthesized
} 

I'm creating an array:

NSMutableArray *myArray; // retained and synthesized

Filling it with several MyClass objects:

MyClass *kat = [MyClass new];
kat.name = @"somestring";
kat.address = @"someotherstring"
[myArray addObject:kat];
[kat release];

How can I get object at some index? The code below keeps giving me null but it should illustrate what I need..

MyClass *obj = (MyClass*)[myArray objectAtIndex:5];
NSLog(@"Selected: %@", obj.address); // = null :(

Is it something wrong with casting or I'm forgetting about something?

Upvotes: 2

Views: 1742

Answers (2)

Eric Abbott
Eric Abbott

Reputation: 95

It's not enough to just declare myArray in an @property/@synthesize pair. You need myArray to be non-nil as well. You need to add myArray = [[NSMutableArray alloc] init]; somewhere above your [addObject:]call.

Additionally, since you've declared the "myArray" variable as retain, if you set another (non-nil) array to myArray through self.myArray = otherArray myArray will be non-nil and retained and ready to accept objects.

Also, if you allocate myArray, don't forget to release it in your class's dealloc method.

Upvotes: 3

bbum
bbum

Reputation: 162712

MyClass *obj = (MyClass*)[myArray objectAtIndex:5];
NSLog(@"Selected: %@", obj.address); // = null :(

If that code is printing (null), it cannot be because the array is empty or objectAtIndex: failed. objectAtIndex: will throw a range exception if you try to access an index beyond the count of objects in the array and an array cannot contain "holes" or nil references.

The only way that code will run without incident is if:

  • myArray is nil; you didn't allocate and/or assign an array instance to myArray.

  • obj.address returns nil; you didn't correctly initialize the instance (which it appears you did).

Upvotes: 6

Related Questions