2012-04-13 1 views
0

가능한 중복 :
Class methods which create new instances사용자 정의 NSObject의 클래스 [CustomObj customObjWithData : 데이터]처럼 인스턴스화

나는있는 NSString, NSArray를하고 같은 같은 같은 클래스의 인스턴스를 에뮬레이션하는 방법 궁금 this : [NSArray arrayWithObject : object] ... inits와 allocs를 없애기 위해서.

나는 실제로 그것이 무엇을하는지 익숙하지 않을 수도 있습니다. Documentation에 따르면 [NSSArray array]는 빈 배열을 만들고 반환합니다. 그게 무슨 뜻입니까, 어떤 배정입니까?

나는 사용자 정의 NSObject의 클래스를 가질 수 싶어 할 : [CustomObj customObjWithData : 데이터]

감사합니다!

당신이 좋아하는 일을 할 필요가
+0

자동으로 릴리즈 된 객체 만 반환하십시오. ARC를 사용한다면 alloc/init 호출의 결과를 반환하면됩니다. –

답변

5

먼저 해당하는 사용자 정의 init... 방법을 쓰기 호출 할 수 있습니다 :

- (id)initWithFoo:(Foo *)aFoo 
{ 
    // Do init stuff. 
} 

그런 다음 사용자 지정 팩토리 메소드를 추가를 그 alloc 및 맞춤 init... 방법으로 전화하십시오 :

+ (id)customObjWithFoo:(Foo *)aFoo 
{ 
    return [[[self alloc] initWithFoo:aFoo] autorelease]; 
} 

ARC로 컴파일하는 경우 autorelease 호출을 생략하십시오.

-1

...

+ (CustomObj *)customObjWithData:(NSData *)data { 
    return [[[CustomObj alloc] initWithData:data] autorelease]; 
} 

... 그리고 initWithData을 구현 : 변수의 초기화를 처리 할 수 ​​있습니다.

+3

항상 초기화 기에서'id'를 반환합니다. 서브 클래 싱을 적절하게 지원하려면 클래스 이름을 하드 코딩하는 대신'[self alloc]'을 사용하십시오. –

0

이들은 클래스 메소드입니다. 대개 인스턴스 init * 메소드도 가지고 있습니다. 예를 들어 ...

- (id)initWithData:(NSData*)data 
{ 
    // Call appropriate super class initializer 
    if (self = [super init]) { 
    // Initialize instance with the data 
    } 
    return self; 
} 

+ (id)customObjWithData:(NSData*)data 
{ 
    return [[self alloc] initWithData:data]; 
} 

지금, 당신은

CustomObj *obj = [CustomObj customObjWithData:data]; 
+0

ARC 아래에 있지 않으면 생성자는 새 객체를 반환하기 전에'autorelease'를 보내야합니다. –

+0

예, 개인적으로는 해당 문제와 직접 관련이없는 게시물의 메모리 관리에 대한 모든 의견을 보는 것을 좋아하지 않습니다. 사람들은 그들이 목표로 삼고있는 메모리 관리 모델을 알고 적절한 코드를 작성해야합니다. 그들이 이미 메모리 관리에 대해 알고 있다면, 그들은이 코드가 ARC라고 가정한다는 것을 이미 알고 있습니다. 그렇지 않으면 Xcode의 ARC 버전을 사용하고있을 것입니다. –

-1

많은 답변이 정확합니다. 나는 자기는 항상 스토리 보드 - 인스턴스를 인스턴스화 도중 쉽게 ALLOC하는 방법을 만들 :

//FooViewController.m

+ (id)create 
{ 
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil]; 

    return [storyboard instantiateViewControllerWithIdentifier:@"FooViewController"]; 
} 

+ (UINavigationController *)createWithNavagionController 
{ 
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil]; 

    FooViewController *fooViewController = [storyboard instantiateViewControllerWithIdentifier:@"fooViewController"]; 

    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:fooViewController]; 

    return navigationController; 
} 

그리고 당신은 매개 변수를 필요로하는 경우, 같은 클래스의 방법 작성 : createWithName을 (있는 NSString *) 이름