這是一個非常基本的問題,但我已經找遍了,並一直無法找到解釋不夠好,我繞過它我的頭一個答案。如何從一個類在另一個(IOS)調用方法
我想要做的是在一個類中我iOS應用程序的創建方法,然後再調用其他類,方法在我的應用程序。有人能夠解釋我需要做什麼來實現這一目標嗎?任何幫助將不勝感激,因爲我迄今爲止的所有嘗試都失敗了!
謝謝。
這是一個非常基本的問題,但我已經找遍了,並一直無法找到解釋不夠好,我繞過它我的頭一個答案。如何從一個類在另一個(IOS)調用方法
我想要做的是在一個類中我iOS應用程序的創建方法,然後再調用其他類,方法在我的應用程序。有人能夠解釋我需要做什麼來實現這一目標嗎?任何幫助將不勝感激,因爲我迄今爲止的所有嘗試都失敗了!
謝謝。
的Objective-C:
你必須導入包含您要使用的方法的類的頭(ClassYouWantToUse.h)到你想使用它的類(TargetClass)。
的TargetClass.h或TargetClass.m內(取決於你的範圍想給它):
#import "ClassYouWantToUse.h"
然後創建要目標類無論是作爲內部使用類的一個實例屬性是這樣的:
@property (nonatomic,strong) ClassYouWantToUse *classObject;
或實例變量是這樣的:
ClassYouWantToUse *classObject;
確保你初始化它! (平日裏的viewDidLoad):
classObject = [[ClassYouWantToUse alloc] init];
現在,你甚至可以從該類任何公開的方法是這樣的:
[classObject theClassMethodWithParam:param1 andSecondParam:param2];
注:的ClassYouWantToUse類中必須有你想訪問的方法通過在頭文件中聲明:
- (void)theClassMethodWithParam:(UIImage*)someImage andSecondParam:(NSString*)someText;
否則,您將無法看到這些方法。
斯威夫特:
即使世界真的沒有什麼特別的地方在迅速,只需添加此作爲參考。
在SWIFT只需創建您要使用的類的實例:
let classObject = ClassYouWantToUse()
,並直接使用它:
classObject.theClassMethodWithParam(param1, andSecondParam:param2)
謝謝**所以**多!你無法想象我已閱讀了多少篇帖子,試圖找出答案。正如我現在想要的那樣工作! – 2012-03-16 12:21:39
路易斯·奧斯卡,你美麗的男人! – Ian 2013-02-22 17:23:00
好奇,現在有兩個ClassToBeUsed實例的正確解決方案是什麼?因爲*類與ClassToBeUsed中的自我背向不一樣?所以在這個例子中,如果我從[something somethingWithParam:blabla andSecondParam:otherbla]引用self,它會引用* something。如果我需要引用ClassToBeUsed的原始實例,該怎麼辦? – rick 2013-07-12 01:26:37
你有兩個基本的選擇。您可以創建或第一類的實例傳遞到第二類,也可以添加一個靜態方法來第一類和直接使用類對象調用它。
舉例來說,假設你有:
@interface ClassA : NSObject {
}
//instance methods
- (int) addNumber:(int)num1 withNumber:(int)num2;
//static/class methods
+ (int) add:(int)num1 with:(int)num2;
@end
@implementation ClassA
- (int) addNumber:(int)num1 withNumber:(int)num2 {
return num1 + num2;
}
+ (int) add:(int)num1 with:(int)num2 {
return num1 + num2;
}
@end
然後,你可以這樣做:
#import "ClassA.h"
@interface ClassB : NSObject {
ClassA* adder;
}
//constructors
- (id) init; //creates a new instance of ClassA to use
- (id) initWithAdder:(ClassA*)theAdder; //uses the provided instance of ClassA
//instance methods
- (int) add2To:(int)num;
//static/class methods
+ (int) add3To:(int)num;
@end
@implementation ClassB
- (id) init {
if (self = [super init]) {
adder = [[ClassA alloc] init];
}
return self;
}
- (id) initWithAdder:(ClassA*)theAdder {
if (self = [super init]) {
adder = theAdder;
}
return self;
}
- (int) add2To:(int)num {
return [adder addNumber:2 withNumber:num];
}
+ (int) add3To:(int)num {
return [ClassA add:3 with:num];
}
@end
注意,在大多數情況下,你可以使用實例的方法,而不是靜態方法。
我覺得你的問題有點含糊。您將在任何基本應用程序中完成此操作。即。調用對象的方法。你可以給代碼示例顯示你正在嘗試做什麼? – drekka 2012-03-16 02:47:22
您可以使用NSNotificationCenter或委託或您的自定義協議.... – 2013-09-26 13:27:25