类类数组的问题

时间:2012-02-27 22:28:28

标签: objective-c arrays nsmutablearray nsarray foundation

嘿伙计们我正在尝试构建一个将NSStrings映射到int的数据库。我有一个名为Movie.h的类,其中每个对象都有一个名称和一个分配的编号:

//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

然后我有另一个名为Map的类,我正在实现与我的“电影”一起玩的功能。其中一个函数叫做insert,它将类movie的对象插入到一个应该存储所有电影的数组中。代码编译,但我的“m_array”似乎没有记录我添加到它的内容。这是代码:

//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;

}

这是我的主要内容:

//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;
}

这是控制台输出:

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

1 个答案:

答案 0 :(得分:2)

看起来您忘了创建数组:

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

没有创建它,它只是nil

相关问题