2017-02-17 98 views
0

比如我有類:有沒有辦法引用自定義類對象的一個​​屬性/方法?

@interface CustomClass: NSObject 
    @property(nonatomic, readwrite) NSString *name; 
    @property(nonatomic, readwrite) NSNumber *value; 
    -(NSDictionary *)getDict; 
@end 

@implementation CustomClass 
-(NSDictionary)getDict 
{ 
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary: @{}]; 
    if(self.name) { 
     dict[@"name"] = self.name; 
    } 
    if(self.value) { 
     dict[@"value"] = self.value; 
    } 
    return dict; 
} 
@end 

然後,我創建一個類的實例:

CustomClass *obj = [[CustomClass alloc] init]; 
obj.name = @"Custom object"; 
obj.value = @1; 

有沒有一種方法指的是,當得到「名」屬性或方法getDict目的?像

NSLog(@"%@", obj); 

只會返回例如'name'屬性?

+0

獲取字典調用[obj getDict]並獲取名稱NSString * name = [obj getDict] [@「name」] – suhit

+1

爲什麼不調用'obj.name'而不是'obj'來檢索它?如果它只是用於日誌,用'return _name;'重寫' - (NSString *)description',但這是誤導。這可能是更好的做'返回[的NSString stringWithFormat:@」 <%@ %p>名稱:%@,[自我類],自我,_name]' – Larme

+0

,我知道,但有沒有辦法不直接引用屬性或方法 – Ratka

回答

1

您應該重寫descriptiondebugDescription

- (NSString *)description 
{ 
    return self.name; 
} 
0

我已經找到一種方法(不知道這是否是正確的方式): 我的自定義類是標誌類MySerializable的子類。現在,如果我有一個數組對象,那麼對於數組中的每個項目,我都會檢查它是否具有MySerializable類型,並將該數組中的對象更改爲[object getDict]。

相關問題