2013-08-21 2 views
2

내지도 객체는 좌표 세트를 가지고 있습니다. 항상 동일한 수의 좌표를 갖는 것은 아닙니다. 자바에서는 객체를 Double[] xpoints으로 선언하고 다음과 같이지도를 인스턴스화 할 때 크기를 설정합니다. xpoints = new double[npoints];objective-c에서 double 배열을 선언합니다.

어떻게하면 objective-c로 할 수 있습니까?

나는 이걸 시도했다 : @property(nonatomic) double * xpoints; 그러나 NSLog로 인쇄 할 때 어떻게 든 그것의 값은 모두 0으로 바뀐다.

지도의 init : 이상한

-(id)initWithXpoints:(double[]) xpointss Ypoints:(double[]) ypointss Npoints:(int)npointss 
{ 
    self = [super init]; 
    if (self) 
    { 
     self.xpoints = xpointss; 
     self.ypoints = ypointss; 
     self.npoints = npointss; 
    } 
    return self; 
} 

뭔가 생각 발생합니다. 지도를 만든 객체에서 xpoints [0]을 인쇄하면 값이 0으로 변경됩니다. 처음 인쇄 할 때 작동합니다. 두 번째로 단지 제로를 인쇄합니다.

나는 init에 보낸 xpointss가 메모리에서 제거 되었기 때문에 발생한다고 생각한다. xpoints 프로퍼티가 포인터라면 어떻게 "인스턴스화"할 수 있습니까?

더 좋은 방법이 있나요? 나는이 같은 임시 xpoints을 만드는 시도 :

double tempxpoints[npointss]; 
double tempypoints[npointss]; 
for (int i = 0; i < npointss; i++) 
{ 
    tempxpoints[i] = xpointss[i]; 
    tempypoints[i] = ypointss[i]; 
} 
self.xpoints = tempxpoints; 
self.ypoints = tempypoints; 

를하지만 여전히 작동하지 않았다

덧붙였다.

편집 : 모든 답변 주셔서 감사합니다. 결국 내 최종 초기화 코드가되었습니다.

-(id)initWithXpoints:(double[]) xpointss Ypoints:(double[]) ypointss Npoints:(int)npointss 
{ 
    self = [super init]; 
    if (self) 
    { 
     _xpoints = [[NSMutableArray alloc] init]; 
     _ypoints = [[NSMutableArray alloc] init]; 
     for (int i = 0; i < npointss; i++) 
     { 
      NSNumber *tempx = [NSNumber numberWithDouble:xpointss[i]]; 
      NSNumber *tempy = [NSNumber numberWithDouble:ypointss[i]]; 
      [_xpoints addObject:tempx]; 
      [_ypoints addObject:tempy]; 
     } 
     _npoints = npointss; 
    } 
    return self; 
} 
+1

'NSArray'를 대신 사용하셨습니까? –

+0

내가 할 수있을 것 같아. 하지만 안드로이드 용으로 만든 앱을 다른 사람이 포팅하는 중이므로 너무 많이 바꾸지는 않을 것입니다. – HSNN

답변

7

배열을 로컬 변수로 할당하면 스택에 할당됩니다. 실행이 기능을 떠나면 해당 메모리 영역이 해제됩니다. 전달할 수있는 배열을 할당하려면 malloc()을 사용해야하고 free()을 사용하여 배열을 해제해야합니다.

// to allocate 
double[] tempxpoints = (double[])malloc(sizeof(double) * npointss); 

// to free when not used any more 
free(tempxpoints); 

실제로는 NSArray이 이러한 경우를 처리하도록 설계되었습니다. ARC를 사용하면 메모리를 확보 할 필요조차 없습니다.

NSMutableArray *tempxpoints = [[NSMutableArray alloc] init]; 
[tempxpoints addObject:@2]; // wrap the double in an NSNumber object 
+0

NSArray는 upwrapped double을 가질 수 없습니다. – Chuck

+0

NSNumbers를 삽입 할 수 있습니다. @ 1, @ 2 ... – allprog

+0

마지막 행에'NSMutableArray'를 의미 할 수도 있습니다. - 응용 프로그램에 따라 다릅니다. 일부 작업 권투 및 unboxing에 대한 수치는 상당한 오버 헤드를 추가 할 수 있습니다. –

3

당신이 그것에 대해 충분히 목표 - C 인 된 경우, NSNumber들로 채우기 NSArray를 사용하여 길이를 지정하지 않을 것입니다. 일반적으로 얼마나 많은 공간이 필요한지에 대한 힌트를 제공 할 수 있지만 Objective-C의 컬렉션은 항상 항상 동적으로 크기가 있습니다.

최근 컴파일러 버전에서 NSArrayarray[x] 표기법을 사용하고 직접 NSNumber과 같은 상수를 쓸 수 있습니다. @4.5f 그 거래를 다정하게하는 경우.

문자 그대로 C 스타일 배열을 원할 경우 C 수준까지 내려야합니다. 그래서, 뭔가 같은 :

@property(nonatomic, readonly) double * xpoints;

그리고 :

-(id)initWithXpoints:(double[]) xpointss Ypoints:(double[]) ypointss Npoints:(int)npointss 
{ 
    self = [super init]; 
    if (self){ 
     size_t sizeOfArraysInBytes = sizeof(double)*npointss; 
     _xpoints = (double *)malloc(sizeOfArraysInBytes); 
     memcpy(_xpoints, xpointss, sizeOfArraysInBytes); 
     /* ... etc ... */ 

     /* you never use self. notation in an init because it's a method call, 
     and method calls on objects that are not yet fully instantiated aren't 
     safe. Sample cause of failure: a subclass overrides the setter */ 
    } 
    return self; 
} 

- (void)dealloc 
{ 
    free(_xpoints); 
    /* ... etc ... */ 
} 

배열 자체가/다른 곳에 쓰기 읽을 수 있습니다 class.xpoints[0]로 (이것은 읽기 전용, 그것은는 것을 지적하지에 포인터입니다) 등

+1

답해 주셔서 감사합니다. 나는 NSMutableArray를 사용하기로 결정 했으므로 NSMutableArray를 할당 해제하는 것에 대해 걱정할 필요가 없습니다. – HSNN

관련 문제