Call Objective-C object method from C function [duplicate] - objective-c

This question already has answers here:
How to call an Objective-C Method from a C Method?
(5 answers)
Closed 8 years ago.
I do have an objective-c object myObject.
Inside this object I do have some C-functions.
static void C_doThing(void) {
...
}
Inside myObject i can just call C_doThing() and the function gets called.
Now I want to call a method of myObject from this C-function.
Is there a way to do this? "Self" is not available inside the C-function.
Thanks

No; the C function is just a plain C function that happens to be defined inside your .m file, but it's not actually "part" of the object (class). It just happens to be stuck sitting there in the same file.
You could pass the object (self in the caller) in as an argument to the function, and then call methods on it.
But you should probably just make it into a normal instance method. You've defined it as static, which means it has no visibility outside of the file. If that's the case, then why not make it a method?
(There may be a small number of good cases for using utility C functions that are used only within a single class implementation, but they're pretty rare and typically around serious performance optimization.)

Related

Swift how to load a class [duplicate]

This question already has answers here:
Method load() defines Objective-C class method 'load', which is not permitted by Swift 1.2
(5 answers)
Closed 6 years ago.
As we knew, when an Objective-C class was loaded the +load method would be called. But in Swift we don't have +load method.
So I tried to invested this. I added a symbol breakpoint at call_load_methods. In Objective-C world. this function will call all the class's +load. But it didn't enter this breakpoint.
So I wondering how to load in Swift. Or can you guys give me more detail a about Swift runtime or something else?
Unfortunately, a load class method implemented in Swift is never
called by the runtime, rendering that recommendation an impossibility.
Instead, we're left to pick among second-choice options:
Implement method swizzling in initialize. This can be done safely, so
long as you check the type at execution time and wrap the swizzling in
dispatch_once (which you should be doing anyway). Implement method
swizzling in the app delegate. Instead of adding method swizzling via
a class extension, simply add a method to the app delegate to be
executed when application(_:didFinishLaunchingWithOptions:) is called.
Depending on the classes you're modifying, this may be sufficient and
should guarantee your code is executed every time.
source

Allow only a particular class to call init in iOS [duplicate]

This question already has answers here:
Singleton pattern in objc, how to keep init private?
(4 answers)
Closed 7 years ago.
I was trying something new so just going through a thought process to allow only my singleton class to create new instance for other classes which are hidden behind it.
I am able to restrict to call the init method using the "unavailable" attribute along with my init method but can I create an exception that only my Singleton class can call the init method.
but can I create an exception that only my Singleton class can call the init method
You can't know who the caller is — see this discussion of the matter — but you can certainly hide the init method by not putting it in your header. A commonly used solution is, if possible, to have the singleton factory method call a "private" initializer and throw an exception on the "public" initializer. Of course that doesn't ultimately prevent anyone from calling the "private" initializer - sorry, Objective-C is too dynamic for that - but it makes it harder to obtain a non-singleton instance by mistake.

Use of "Self" keyword in Objective-C [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Objective-C - When to use ‘self’
I can't understand very well the importance and the usage of the "self" keyword in objective-c. It's my first OOP language so i got stuck on some concepts.
When i should use "self"? Why is it useful?
Thanks for the answers!
Edit: I can't understand why is this a duplicated post of Objective-C - When to use 'self' when there there is not the explanation of "Self" that i wanted.
self is a special variable in Objective-C, inside an instance method this variable refers to the receiver(object) of the message that invoked the method, while in a class method self will indicate which class is calling.
self refers to the actual object that is executing the current method, it is an invisible argument passed automatically by the runtime environment to your instance methods.

What is the (id) mean in the init method? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the meaning of id?
I am the newbie to Ios programming.
I saw the following declaration
- (id)init
what does (id) mean here?
id denotes a type which is compatible with any object. The notation
- (id)init
means the init instance method of your class; typically it's used to initialize the instantiated object after memory allocation (usually done using alloc). In Objective-C, methods' return type is declared by putting the type in parentheses before the method name. So, here it means that the init method may return any Objective-C object.
But you should really, really google an Objetive-C tutorial and read it. This is such a fundamental thing for which there is no excuse for not reading a tutorial or other documentation.
id is the plain C compatible type that represents an Objective-C object. This allows C source code to store, and interact with, Objective-C objects.
The reason for it to be of type 'id' is that the -init method is inherited all the way up from NSObject (in objective-C you can not overload methods, hence you can not change the argument/retrurn value types when subclassing). Since 'id' works with any object, this is OK.
EDIT It seems that specifying a concrete class as the return type of -init is OK, even though you are ultimately overriding '-[NSObject init]'.
I guess the use of 'id' is just a custom?
The fact that 'id' acts as a "generic Objective-C object pointer" that accepts any object type on assignment remains unchanged, though.
-(id)init is called to initialize the variables inside an object and do any necessary setup (it's basically the constructor).
A possiable duplication can be
What's the -(id)init method good for?

Objective C message dispatch mechanism [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 months ago.
The community reviewed whether to reopen this question 7 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I am just staring to play around with Objective C (writing toy iPhone apps) and I am curious about the underlying mechanism used to dispatch messages. I have a good understanding of how virtual functions in C++ are generally implemented and what the costs are relative to a static or non-virtual method call, but I don't have any background with Obj-C to know how messages are sent. Browsing around I found this loose benchmark and it mentions IMP cached messages being faster than virtual function calls, which are in turn faster than a standard message send.
I am not trying to optimize anything, just get deeper understanding of how exactly the messages get dispatched.
How are Obj-C messages dispatched?
How do Instance Method Pointers get cached and can you (in general) tell by reading the code if a message will get cached?
Are class methods essentially the same as a C function (or static class method in C++), or is there something more to them?
I know some of these questions may be 'implementation dependent' but there is only one implementation that really counts.
How are Obj-C messages dispatched?
Objective-C messages are dispatched using the runtime's objc_msgSend() function. Shown in the Apple docs, the function takes at least 2 arguments:
The receiving object
The selector of the message
[A variable list of arguments to the message being sent.]
Instances of a class have an isa pointer, which is a pointer to their class object. The selectors of methods in each object are stored in a "table" in the class object, and the objc_msgSend() function follows the isa pointer to the class object, to the find this table, and checks whether the method is in the table for the class. If it cannot find it, it looks for the method in the table of the class's superclass. If not found, it continues up the object tree, until it either finds the method or gets to the root object (NSObject). At this point, an exception is thrown.
How do Instance Method Pointers get cached and can you (in general) tell by reading the code if a message will get cached?
From Apple's Objective-C runtime guide on Messaging:
To speed the messaging process, the runtime system caches the selectors and addresses of methods as they are used. There’s a separate cache for each class, and it can contain selectors for inherited methods as well as for methods defined in the class. Before searching the dispatch tables, the messaging routine first checks the cache of the receiving object’s class (on the theory that a method that was used once may likely be used again). If the method selector is in the cache, messaging is only slightly slower than a function call. Once a program has been running long enough to “warm up” its caches, almost all the messages it sends find a cached method. Caches grow dynamically to accommodate new messages as the program runs.
As stated, caching starts to occur once the program is running, and after the program has been running long enough, most of the method calls will run through the cached method. As it also says, the caching occurs as the methods are used, so a message is only cached when it is used.
Are class methods essentially the same as a C function (or static class method in C++), or is there something more to them?
Class objects handle method despatch in a similar manner to that of instances of classes. Each class object has an object that stores its own class methods, in an object called a metaclass. The class object has its own isa pointer to its metaclass object, which in turn has super metaclass objects, which it can inherit class objects from. Method dispatch to class methods is as so:
The dispatch system follows the class object's isa pointer to the metaclass object
The metaclass object's method table is searched for the class method.
If not found, the search continues to the metaclass object's superclass, where the search continues.
This process repeats until either the method is found, or until it gets to the root metaclass, and an exception is thrown.
Dispatch mechanisms
It is used to find a necessary executable code when method was called(message sent)
Inline
Static(Direct)(C, Java final, C++ default, Swift static, final) - compiler knows the necessary method realisation at compile-time.
Dynamic - is based on witness table(virtual table, dispatch table) and it introduce polymorphism
Table, V-Table(C++ virtual, Java default, Swift default) - Every object has a reference to class which has a table with all method addresses(super, overrides, new). SIL contains vtable or witness_table
Message(Objective-C, Swift dynamic) - Every object has a reference(isa) to class which contains a reference to superclass and dispatch table(which contains only realised methods(new and which were overhead)) and don't contain methods from super. If method was not found in current dispatch table, it continue searching in superclass's dispatch table. This process is optimised by caching. SIL contains volatile
Objective-C Message Dispatch
For example
class A {
func foo1() {}
func foo2() {}
}
class B: A {
override func foo2() {}
func foo3() {}
}
Objective-C obc_msgSend
id obc_msgSend(id self, SEL op, ...)
// self - object which receive a message
// op - selector of method
//... - arguments
If method implementation was not found for given selector you see next error
unrecognized selector sent to instance