2012-07-06 5 views
2

NSMutableArray에 일부 데이터를 저장하려고합니다.NSMutableArray : 구조체 추가 및 추출

person h1; 
h1.time = 108000; 
strcpy(h1.name, "Anonymous"); 
[highscore insertObject:[NSValue value:&h1 withObjCType:@encode(person)] atIndex:0]; 

그래서, 나는이 방법으로 추출하려고 :

NSValue * value = [highscore objectAtIndex:0]; 
person p; 
[value getValue:&p]; 
NSLog(@"%d", p.time); 

문제가 있다는 것입니다 이것은 코드가 사람을 추가하는 것입니다

typedef struct{ 
    int time; 
    char name[15]; 
}person; 

: 이것은 내 구조체입니다 최종 로그에 108000이 표시되지 않습니다!
무엇이 잘못 되었나요?

+0

를 인쇄하지 않는 이유는 임의 스택 쓰레기로 가득 왼쪽되는 것은 당신이 아니라 교류 구조체를 사용하는 특별한 이유가 person p 당신, 아무것도하지 않는 실제 물건보다? 그렇지 않으면 물건을 가지고 가십시오. – Regexident

+0

두 가지 유형의 데이터 (int 및 string)를 동일한 인덱스에 저장하는 다른 방법을 모른다. 나는 "페르소나"를 정정했다, 미안. – charles

+0

@ user1431646 사용자 지정 클래스를 만듭니다. –

답변

1

이 내 최초의 코멘트에 명시된 바와 같이이 순수한 구조체로 이런 종류의 작업을하는 이유는 거의 없습니다. 대신 실제 클래스 객체로 이동합니다

애플의 문서 ObjC 2.0이 빠른 튜토리얼을 볼뿐만 아니라 읽을 수 있습니다 다음은 구문에 익숙하지 않은 경우

:

사람 클래스 :

// "Person.h": 
@interface Person : NSObject {} 

@property (readwrite, strong, nonatomic) NSString *name; 
@property (readwrite, assign, nonatomic) NSUInteger time; 

@end 

// "Person.m": 
@implementation Person 

@synthesize name = _name; // creates -(NSString *)name and -(void)setName:(NSString *)name 
@synthesize time = _time; // creates -(NSUInteger)time and -(void)setTime:(NSUInteger)time 

@end 
,536,913 63,210

클래스 사용 :

- (NSString *)description { 
    return [NSString stringWithFormat:@"<%@ %p name:\"%@\" time:%lu>", [self class], self, self.name, self.time]; 
} 

그냥 로깅이 작업을 수행 할 수 있습니다 :

#import "Person.h" 

//Store in highscore: 

Person *person = [[Person alloc] init]; 
person.time = 108000; // equivalent to: [person setTime:108000]; 
person.name = @"Anonymous"; // equivalent to: [person setName:@"Anonymous"]; 
[highscore insertObject:person atIndex:0]; 

//Retreive from highscore: 

Person *person = [highscore objectAtIndex:0]; // or in modern ObjC: highscore[0]; 
NSLog(@"%@: %lu", person.name, person.time); 
// Result: "Anonymous: 108000" 

당신은 또한 description 방법을 구현하는 Person을 할 수 있습니다 디버깅을 간소화하기 위해

NSLog(@"%@", person); 
// Result: "<Person 0x123456789 name:"Anonymous" time:108000> 
+0

감사합니다. 모든 것을 수정했지만, 실수 한 것은 배열을 초기화하는 것을 잊었습니다! – charles

+0

@ user1431646 : 여전히 개체로 이동하십시오. 하지 않을 이유가 없습니다. 그러나 그것에 찬성하여 수백. 쉽게 문자열을 처리하고 메모리 할당을 쉽게 시작할 수 있습니다. – Regexident

0

구현할 목표 -C 객체로서 사람과 혜택을 얻을 :

Person.h :

@interface Person : NSObject 
{ 
    int _time; 
    NSString *_name; 
} 

@property (assign, nonatomic) int time; 
@property (retain, nonatomic) NSString *name; 

@end 

Person.m :

#import "Person.h" 

@interface Person 
@synthesize time = _time; 
@synthesize name = _name; 

- (id)init 
{ 
    self = [super init]; 
    if (self != nil) 
    { 
     // Add init here 
    } 
    return self; 
} 

- (void)dealloc 
{ 
    self.name = nil; 
    [super dealloc]; 
} 

@end 
+1

인터페이스에서 private 멤버를 선언 할 필요가 없으며'@ property'와'@ synthesize'만으로 충분합니다.또한 ARC에서 dealloc (및 init)은 둘 다 필요하지 않습니다. 4.5를 사용하면'@ synthesize'도 제거 할 수 있으며 속성 선언 만 남겨 둡니다. –

+0

@HampusNilsson 이것은 내가 선호하는 스타일이며이 구현은 거의 모든 컴파일러와 메모리 환경에서 작동해야합니다. – trojanfoe

2

코드가 정확하고 올바르게 작동합니다. 따라서 추론합니다. highscore을 초기화하지 않았습니다. 따라서 insertObject:atIndex: 메시지를 보낼 때 아무런 반응이 없습니다. 그런 다음 objectAtIndex: 메소드를 보내면 되돌릴 수 없습니다. 당신이 전무 NSValue *valuegetValue:를 보낼 때, 그래서 당신의 NSLog가 108000.