Question

Hey guys I am trying to build a database that maps NSStrings to int. I have on class called Movie.h where each object has a name and a number assigned:

//Movie.h
@interface Movie : NSObject
{
    int m_num;
    NSString *m_name;
}
@property int m_num;
@property(nonatomic, retain) NSString *m_name;
@end

//Movie.m
@implementation Movie
@synthesize m_num, m_name;
@end

I then have another class called Map where I am implementing functions to play with my "Movies". One of the function is called insert, and it inserts an object of class movie into an array where all movies should be stored. The code compiles but my "m_array" does not seem to keep a record of what I add to it. Here is the code:

//Map.h
#import "Movie.h"
@interface Map : NSObject
{
@private
    int m_count;
    NSMutableArray *m_array;
}
@property int m_count;
@property(nonatomic, retain) NSMutableArray *m_array;
-(bool) contain: (NSString *) name;
-(bool) insert: (NSString *) name: (int) chap;
@end

//Map.m
@implementation Map
@synthesize m_count, m_array;

//Constructor
-(id) init{
    if (self = [super init]){
        m_count = 0;
    }
    return self;
}
-(bool) contain: (NSString *) name{
    bool b = false;
    for (int i = 0; i < m_count; i++) {
        Movie *m = [[Movie alloc]init];
        m = [m_array objectAtIndex:i];
        NSLog(@"%@ came out in %i", m.m_name, m.m_num);
        if (m.m_name == name) {
            b = true;
        }
    } 
    return b;
}
-(bool) insert:(NSString *) name: (int) chap{
    Movie *m1 = [[Movie alloc]init];
    m1.m_name = name;
    m1.m_num = chap;
    [m_array addObject:m1];
    NSLog(@"Here is the object %@",[m_array objectAtIndex:m_count]);
    m_count++;
    return true;
}
@end

-(bool) upgrade:(NSString *)name :(int)chap{
    if(![self contain:name])
        return false;
    for (int i = 0; i < m_count; i++){
        Movie *m = [[Movie alloc]init];
        m = [m_array objectAtIndex:i];
        if(m.m_name == name)
            m.m_num = chap;
    }
    return true;

}

Here's my main:

//main.m
#import "Map.h"

int main (int argc, const char * argv[])
{
    @autoreleasepool 
    {
        Map *m = [[Map alloc]init];
        [m insert:@"James Bond" :2001];
        if (![m contain:@"James Bond"]) {
            NSLog(@"It does not work");
        }
    }
    return 0;
}

Here's the console output:

2012-02-27 14:20:04.923 myMap[3926:707] Here is the object (null)
2012-02-27 14:20:05.036 myMap[3926:707] (null) came out in 0
2012-02-27 14:20:05.037 myMap[3926:707] It does not work
Was it helpful?

Solution

It looks like you forgot to create the array:

- (id)init
{
  self = [super init]
  if (nil != self) {
    m_count = 0;
    m_array = [NSMutableArray new]; << here
  }
  return self;
}

Without creating it, it's just nil.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top