C 函数与 Objective-C 方法? [英] C function vs. Objective-C method?

查看:28
本文介绍了C 函数与 Objective-C 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两者有什么区别?如果我正在编写程序,我什么时候需要这个:

What is the difference between the two? If I'm writing a program, when would I need a this:

void aFunction() {
    //do something
}

我什么时候需要这个:

-(void)aMethod {
    //do something else
}

推荐答案

实际上,Objective-C 方法只是一个 C 函数,两个参数总是出现在开头.

Actually, an Objective-C method is just a C function with two arguments always present at the beginning.

这个:

-(void)aMethod;

完全等同于:

void function(id self, SEL _cmd);

Objective-C 的消息传递是这样的:

Objective-C's messaging is such that this:

[someObject aMethod];

完全等同于此(几乎 - 存在超出此答案范围的可变参数 ABI 问题):

Is exactly equivalent to this (almost -- there is a variadic argument ABI issue beyond the scope of this answer):

objc_msgSend(someObject, @selector(aMethod));

objc_msgSend() 找到该方法的适当实现(通过在 someObject 上查找),然后通过尾调用优化的魔力,跳转到该方法的实现,对于所有的意图和目的,都与 C 函数调用完全一样,如下所示:

objc_msgSend() finds the appropriate implementation of the method (by looking it up on someObject) and then, through the magic of a tail call optimization, jumps to the implementation of the method which, for all intents and purposes, works exactly like a C function call that looks like this:

function(someObject, @selector(aMethod));

从字面上看,Objective-C 最初只是作为 C 预处理器实现的.你在 Objective-C 中可以做的任何事情都可以用直接的 C 重写.

Quite literally, Objective-C was originally implemented as nothing but a C preprocessor. Anything you can do in Objective-C could be rewritten as straight C.

然而,这样做将是一件非常痛苦的事情,除了令人难以置信的教育体验之外,不值得花时间.

Doing so, however, would be a complete pain in the ass and not worth your time beyond the incredibly educational experience of doing so.

通常,在使用直接的 C goop 时,您在与对象和函数交谈时使用 Objective-C 方法.鉴于几乎所有 Mac OS X 和 iOS 都提供了 Objective-C API——对于 UI 级别的编程入口点当然完全如此——那么您大部分时间都使用 Obj-C.

In general, you use Objective-C methods when talking to objects and function when working with straight C goop. Given that pretty much all of Mac OS X and iOS provide Objective-C APIs -- certainly entirely so for the UI level programming entry points -- then you use Obj-C most of the time.

即使在编写您自己的相对独立的模型级代码时,您通常也会使用 Objective-C,因为它在状态/数据和数据之间提供了一种非常自然的粘合剂.功能,面向对象编程的基本租户.

Even when writing your own model level code that is relatively standalone, you'll typically use Objective-C simply because it provides a very natural glue between state/data & functionality, a fundamental tenant of object oriented programming.

这篇关于C 函数与 Objective-C 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆