0

I have an array in which I'm adding objects, but the array is remaining empty even after adding the objects. Here are the code:

Event.h

@interface Event : NSObject
@property NSString *name;
@end

Code where objects are added to the array

NSMutableArray *events;
NSArray *event_string = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];

    for (NSString *currentEventString in event_string) {
        Event *currentEvent = [Event new];
        [currentEvent setName:currentEventString];
        [events addObject:currentEvent];

    }
    NSLog(@"Number of events:%d",[events count]);

I'm getting this output:

Number of events:0
1
  • 2
    Initialize events array Commented Nov 26, 2013 at 11:32

3 Answers 3

3

You have to init this array first.

NSMutableArray *events = [NSMutableArray new];
Sign up to request clarification or add additional context in comments.

Comments

2

You have to initiate events array as following:

NSMutableArray *events = [[NSMutableArray alloc]init];

Comments

2

What Tomasz said - you need to allocate and initialize your array. Right now the pointer to the array object is null.

The reason you get the strange results is that Objective C (unlike languages such as Java, C++ and C#) will happily let you invoke methods on a null object without crashing or throwing exceptions. The result is then "0" values such as null for pointers/objects, 0 for calculations etc.

It's a little different, but inpractice it works well, and simplifies many algorithms.

Comments

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.