2012-09-14 38 views
0

我的iPhone應用程序中的視圖控制器可以從UIViewControllerUITableViewController擴展。我需要爲它們添加一個屬性,以便我可以在控制器之間傳遞用戶信息。我知道的解決方案是添加一個BaseViewController和一個BaseTableViewController,將它們添加到它們,然後讓所有控制器從它們繼承。將屬性添加到iPhone應用程序中的所有視圖控制器

重複財產BaseViewControllerBaseTableViewController似乎並不是我最優雅的解決方案。有更好的嗎?

謝謝!

+0

這裏的解釋[BJECTIVE-C類:我可以添加一個屬性並不在我的類的方法?] [1] [1]:HTTP:/ /stackoverflow.com/questions/2520889/objective-c-categories-can-i-add-a-property-for-a-method-not-in-my-category – Mitrodan

回答

0

由於擴展名不適用於您的情況,您可以在UIViewController上編寫一個類別,並使用objc_getAssociatedObject來存儲您想要的數據並使用objc_getAssociatedObject檢索它。但是你應該小心使用這個選項。

static NSString *key = @"example"; 

- (void)setExampleProperty:(id)value { 
    objc_setAssociatedObject(self, (__bridge void *)key, value, OBJC_ASSOCIATION_RETAIN); 
} 

- (id)exampleProperty { 
    return objc_getAssociatedObject(self, (__bridge void *)key); 
} 

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html

+0

甜蜜!這就是我想要的。謝謝! –

相關問題