2

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?

2
  • 1
    Have you actually created the NSMutableArray *myArray, or only declared it? You'll need a line like [[NSMutableArray alloc] init] somewhere. Commented Mar 25, 2011 at 17:11
  • you should check the contents of your array in nslog first, if that is null then may be you should show us the code where you have initialize your mutable array. Commented Mar 25, 2011 at 17:16

2 Answers 2

6
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).

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, such a simple mistake, I concentrated on the MyClass object instead of myArray and I really didn't alloc it. But I'm still learning, thanks for explaining!
3

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.

1 Comment

Better to create it with "self.myArray = [NSMutableArray array]". Otherwise you'll need to release it twice - once to balance the ownership implied by the use of +alloc, and again to balance the assignment to a retained property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.