View Controller에 클래스 객체 배열 배열을 저장해야합니다.
-
16-09-2019 - |
문제
여러분을위한 iPhone 질문! 서버에서 XML을 다운로드하여 다른 배열의 일부인 배열로 처리하는 nsurlConnection이 있습니다. 나는 얼마나 많은 객체가 필요한지 알 수 없으므로 미리 nsarray를 할당 할 수 없습니다. 내 질문은 다음과 같습니다.
클래스 레벨에서 NSARRAY로서 부모 배열을 작성하고 데이터를 임시 NSMutableARRAY에 저장 한 후에 배정하는 것이 더 나을까요? 프로그램 실행이 끝날 때 해제하는 것 외에 다른 배열을 수정할 필요는 없다는 점은 주목할 가치가 있습니다.
해결책
나는 그것이 정말로 중요하다고 생각하지 않습니다.
현재 시작 iPhone 3 개발 도서를 읽고 있으며 일반적으로 데이터를로드하는 것은 다음과 같이 수행됩니다. NSARRAY 속성이 있습니다.
@interface
{
...
NSArray *listOfObjects;
...
}
@property (nonatomic, retain) NSArray *listObObjects;
...
그런 다음 nsmutablearray를 만들고 데이터를로드하고 속성을 설정합니다.
NSMutableArray *array = [[NSMutableArray alloc] init]; // ?
// load the XML into array here
...
self.listOfObjects = array;
[array release];
그런 다음 ListOfObjects는 실제로 nsmutableArray 일지라도 nsarray (불변)로 취급됩니다.
다른 팁
아마도 당신이하고 싶은 것은 XML에서 대표하는 것과 일치하는 클래스를 만드는 것입니다. 예를 들어 XML이 다음과 같이 보입니다.
<peopleList>
<person>
<name>Joe</name>
<possession>Shovel</possession>
</person>
<person>
<name>Sam</name>
<possession>Shovel</possession>
<possession>Fork</possession>
<possession>Backpack</possession>
</person>
</peopleList>
Peoplelist 클래스와 개인 수업이 있어야합니다. Peoplelist 클래스에서 인스턴스화 된 객체에는 하나 이상의 사람 객체가 포함 된 첫 번째 배열이 있습니다. Person Objects는 또한 소유물을 잡을 배열이 있습니다 (이 경우 문자열입니다. 필요한 경우 소유 물체가 될 수 있음)이 경우에도 개인 클래스에도 다른 속성이 있습니다. '이름'도 있습니다. 또한 문자열입니다.
예를 들어:
@interface PeopleList {
NSMutableArray *persons; // An array to store the Person objects
}
@property (nonatomic, retain) NSMutableArray *persons;
@end
@interface Person {
NSString *name;
NSMutableArray *possesions; //An array to store this Person's possesion strings
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSMutableArray *possesions;
@end
이 객체의 init 메소드에서는 배열을 할당/시작하여 객체를 수신 할 준비가되어 있어야합니다. 그리고 내가 그들을 할당했기 때문에, 내 수업은 석방에 대한 책임이 있습니다.
@implementation PeopleList
-(id) init {
if (self = [super init]) {
persons = [[NSMutableArray alloc] init];
}
}
-(void) dealloc {
[persons release];
[super dealloc];
}
@end
@implementation PeopleList
-(id) init {
if (self = [super init]) {
possesions = [[NSMutableArray alloc] init];
}
}
-(void) dealloc {
[possesions release];
[super dealloc];
}
@end
이 작업이 완료되었으므로 계단식 배열의 데이터 구조를 설정할 수 있습니다. Peoplelist 태그를 만날 때 XML을 구문 분석 할 때 다음을 수행합니다.
currentPeopleList = [[PeopleList alloc] init];
그리고 당신이 사람을 만날 때, tage는 다음을 수행합니다.
currentPerson = [[Person alloc] init];
[peopleList.persons addObject: person];
소유물 :
[currentPerson.possesion addObject: contentsOfCurrentElement];
또는 이름 :
currentPerson.name = contentsOfCurrentElement;
그러나보다 구체적인 질문에 대답하기 위해 데이터를 임시 NSARRAY에 저장하지 않고 NSMUTABLEARRAY에 복사하지 않습니다. 그렇게함으로써 성능 게인이 거의 없으며, CPU 사이클을 태우고 메모리가 사본을 수행합니다.