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

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

问题描述

两者有什么区别?如果我写一个程序,我什么时候需要一个这样的:

 无效机能缺失(){
    //做一点事
}

,当我需要这样的:

   - (无效){amethod方法
    //做别的事情
}


解决方案

其实,一个Objective-C的方法就是有两个参数的C函数总是present开头。

   - (无效)amethod方法;

是完全等价的:

  void函数(ID自我,SEL _cmd);

目标-C的消息是这样的,这样的:

  [someObject amethod方法]。

完全等同于本(几乎是 - 有一个可变参数的参数ABI的问题超出了这个答案的范围内):

  objc_msgSend(someObject,@selector(amethod方法));

objc_msgSend()找到合适的实施方法(通过看它挂在 someObject ),然后通过尾部调用优化的魔力,跳转到执行其中,对于所有意图和目的,作品就像一个C函数调用,看起来像这样的方法:

 功能(someObject,@selector(amethod方法));

毫不夸张地说,Objective-C的最初实现的不过是一个C preprocessor。的任何的你可以在Objective-C这样做可以改写直℃。

这样做,但是,这是在屁股疼痛完全不值得你的时间超出了这样做的令人难以置信的教育经验。


在一般情况下,你用传统的C粘性物质从中工作时谈话的对象和函数时使用Objective-C的方法。鉴于pretty多所有的Mac OS X和iOS提供的Objective-C的API - 当然完全是这样的UI级编程的切入点 - 然后使用对象 - 大部分时间

甚至写自己的模型级code是相对独立的时候,你通常会使用的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
}

and when would I need this:

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

解决方案

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

This:

-(void)aMethod;

Is exactly equivalent to this:

void function(id self, SEL _cmd);

Objective-C's messaging is such that this:

[someObject aMethod];

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() 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));

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.


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.

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天全站免登陆