2013-01-19 7 views
1

iOS 개발을 처음 사용합니다.iOS에서 객체에 값을 설정할 수 없습니다.

Pet *selectedPet; 

-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{   
UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath]; 
NSString *currentPetTemp,*currentBreedTemp; 
currentPetTemp = cell.textLabel.text; 
currentBreedTemp = cell.detailTextLabel.text; 
selectedPet.petName = currentPetTemp; 
selectedPet.petBreed = currentBreedTemp; 
NSLog(@"%@ Name1: %@",selectedPet.petName,currentPetTemp); 

return indexPath; 

}

:

나는 유형 애완 동물의 선언 된 개체에 대한 값을 설정하려고 내 방법 중 하나에서

@interface Pet : NSObject 
@property(nonatomic, strong) NSString *petName; 
@property(nonatomic, strong) NSString *petBreed; 
@end 

애완 동물

라는 클래스를 가지고 NSLog는 'currentPetTemp'에 대해 올바른 값을 표시하지만 selectedPet.petName에 대해서는 'null'을 표시합니다.

도움을 주시면 감사하겠습니다.

Pet *selectedPet=[[Pet alloc]init]; 

또는

Pet *selectedPet=[Pet new]; 

편집

:이 경고가 표시됩니다

로 의견 Initializer element is not a compile time constant 당 당신이 정의 당신은 havenot

답변

4

는 ... 다음을 수행 초기화 어떤 방법의 범위를 벗어나는 변수. 이 위치는 상수 값에만 사용됩니다.

viewDidLoad/init/awakeFromNib에 alloc-init가 필요합니다.

+1

고마워하지만 이제는 "Initializer element is compile time constant"오류가 발생합니다. – Abhi

+0

new는 objective-c에서 일반적인 생성자 메서드 이름이 아닙니다. 객체의 빈 인스턴스를 만드는 Class 메소드를 만들려면 NSArray의 예제를 따라 가면서'+ (instancetype) pet' 메소드를 생성해야한다 :'[Pet pet];' – jackslash

+0

I 어떤 디폴트 값이 제공되지 않으면 코딩의 스타일로서'new'을 사용하십시오. –

1

두 가지 문제가 있습니다. 첫 번째 코드는 Pet *selectedPet; 코드 줄의 위치입니다. 만약 당신이 그것을 .mile 파일에 넣는다면 그것은 전역 변수가 될 것이다; 이것은 아마도 당신이 원하는 것이 아닙니다. 인스턴스 변수로 만들고 싶을 수도 있습니다. 당신의하는 .m 파일의 상단에 뭔가 같은 :

@implementation MyViewController { 
    Pet *selectedPet; 
} 

두 번째 문제는 selectedPet의 기본값은 nil 때문이다; 즉, 그것은 비어 있습니다. 먼저 초기화해야합니다. 나는 새로운 애완 동물 객체를 생성 한 후 이름과 유형 설정이 같은, 제안 :

-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{   
    UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath]; 
    selectedPet = [[Pet alloc] init]; 
    selectedPet.petName = cell.textLabel.text; 
    selectedPet.petBreed = cell.detailTextLabel.text; 
    NSLog(@"%@ Name1: %@",selectedPet.petName,currentPetTemp); 

    return indexPath; 
} 

(이것은 당신이 ARC를 사용하는 가정을, 그렇지 않으면, 당신은 몇 가지 메모리 관리를 할 필요가있다.)

관련 문제