I come from the Java world, so to me it's all object.foo()
, but in Objective C, is object messaging the only way to invoke a method?
我来自Java世界,所以对我而言,它都是object.foo(),但在Objective C中,对象消息传递是调用方法的唯一方法吗?
[object foo];
4 个解决方案
#1
1
The first thing that comes to mind is using @property and dot-notation. A class with @property named 'foo' allows you to do like this:
首先想到的是使用@property和dot-notation。 @property名为'foo'的类允许您这样做:
anInstance.foo = @"bar";
which literally translates at compile-time to
从字面上翻译成编译时
[anInstance setFoo:@"bar"];
(similar with "getters")
(与“getters”类似)
The other ways are more advanced, such as using NSObject's performSelector: method, or other systems such as NSInvocation, etc. Going deeper, there are ways to call methods in the runtime, with c functions (all of this syntax eventually boils down to calling c-functions anyway); but I'm sure that's not what you are after.
其他方式更高级,例如使用NSObject的performSelector:方法,或其他系统,如NSInvocation等。更深入,有一些方法可以在运行时调用方法,使用c函数(所有这些语法最终都归结为调用无论如何c函数);但我确信那不是你追求的。
#2
4
You can use KVC:
你可以使用KVC:
[label setValue:@"Some text" forKey:@"text"];
#3
1
Yes. You can use dot syntax to get or set Objective C properties. So for example setting text on a UILabel *label can be done either [label setText:@"some text"];
or label.text = @"some text";
是。您可以使用点语法来获取或设置Objective C属性。因此,例如,在UILabel *标签上设置文本可以[标签setText:@“some text”];或label.text = @“some text”;
#4
1
For pedantry's sake, why not get low-level:
为了迂腐,为什么不低级:
objc_msgSend(object, sel_getUid("foo"), errVar);
#1
1
The first thing that comes to mind is using @property and dot-notation. A class with @property named 'foo' allows you to do like this:
首先想到的是使用@property和dot-notation。 @property名为'foo'的类允许您这样做:
anInstance.foo = @"bar";
which literally translates at compile-time to
从字面上翻译成编译时
[anInstance setFoo:@"bar"];
(similar with "getters")
(与“getters”类似)
The other ways are more advanced, such as using NSObject's performSelector: method, or other systems such as NSInvocation, etc. Going deeper, there are ways to call methods in the runtime, with c functions (all of this syntax eventually boils down to calling c-functions anyway); but I'm sure that's not what you are after.
其他方式更高级,例如使用NSObject的performSelector:方法,或其他系统,如NSInvocation等。更深入,有一些方法可以在运行时调用方法,使用c函数(所有这些语法最终都归结为调用无论如何c函数);但我确信那不是你追求的。
#2
4
You can use KVC:
你可以使用KVC:
[label setValue:@"Some text" forKey:@"text"];
#3
1
Yes. You can use dot syntax to get or set Objective C properties. So for example setting text on a UILabel *label can be done either [label setText:@"some text"];
or label.text = @"some text";
是。您可以使用点语法来获取或设置Objective C属性。因此,例如,在UILabel *标签上设置文本可以[标签setText:@“some text”];或label.text = @“some text”;
#4
1
For pedantry's sake, why not get low-level:
为了迂腐,为什么不低级:
objc_msgSend(object, sel_getUid("foo"), errVar);