嘿傢伙我試圖建立一個數據庫,將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
然後我有另一個類調用地圖,我實現的功能與我的「電影」玩。其中一個函數稱爲insert,它將類電影的對象插入到應該存儲所有電影的數組中。代碼編譯,但我的「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
爲什麼你有'm_count'變量?只需使用數組的'count'方法即可。 – 2012-02-27 22:32:30
哦,你是對的。我這樣做是因爲我已經用C++完成了這個類,我只是重寫了Objective-C中的代碼。 – solalito 2012-02-27 23:01:08