Do "dynamic ivars" break the "strict superset of C" paradigm for Objective-c? - objective-c

Thank you to Yuji for answering another question I had and pointing me to this article about dynamic ivars in Objective-C.
However, as explained in my other question the sizeof operator now behaves inconsistently. In short, sizeof will not take into account dynamic ivars from outside the class .m file but will take them into account inside the .m file after the #synthesize declarations that create the dynamic ivars.
So my question is does this break the idea that Objective-C is a strict superset of C?

No. All valid C code remains valid Objective-C code with the same meaning it has in C, so Objective-C is still a strict superset. Keep in mind that a superset is allowed to have features not found in a subset — that's the whole reason Objective-C can have all the additional capabilities and syntax that it does while remaining 100% C-compatible.
What this does affect is the implementation detail that Objective-C classes are essentially C struct types with a set of functions that act on them. Note that similar functionality to objC_setAssociatedObject() could be implemented for a CoreFoundation-style pure C struct without changing the C language itself at all — and it would have the similar side effect of making sizeof() not give a fully "accurate" idea of all the data the struct encompasses.

No. If you run Objective-C code through a C compiler it never would have compiled anyway. If you run C code through an Objective-C compiler it will behave exactly as if you had run it through a C compiler (barring compiler bugs).
If you ever find yourself writing sizeof(MyObjectiveCClass) you are almost certainly doing something horribly wrong that will be completely broken.

Related

Return type differs in implementation for objective C protocols

I have a protocol that has a method returning NSArray*.
In the implementation I had made the return type of that method to be NSView*
I see this is happening only in case of Objective C class pointers and not in other cases like returning void vs returning int.
I would expect a complier warning at the minimum but the compilation happens just fine.
#protocol prot <NSObject>
-(NSArray*)array;
#end
#interface impl : NSObject<prot>
#end
#implementation impl
//Should return NSArray. Returns NSView instead
- (NSView *)array
{
return nil;
}
#end
First things first:
impl should be Implementation since class names are written in upper camel case and abbreviations are bad(TM). Moreover, Class is a class pointer, NSView* and NSArray* are instance pointers.
To your Q, even I'm a bit tired of this discussion (dynamic vs. static typing, early vs. late binding):
A: Why should the compiler warn? Both are instance pointers and maybe the messages sent to the object are supported by both. The compiler does not care about binding, it is done at runtime.
B: But this is very unsafe!
A: Did you ever ship code with such an error?
B: No. But it is unsafe by theory.
A: Yes, that's true for alle theories that ship code without running it at least one time.
B: But you have to admit, that this is more unsafe than type checking at compile time.
A: Yes, theoretically that's true.
B: So why do you support it?
A: Because there are many situations in which dynamic typing has advantages. I. e. it is very easy to write generic code without having templates. (Even sometimes they are called generics, they are still silly templates.) It is very easy to give around responsibility, what needs contra-conceptual extensions in other languages (signals & slots in C++, delegates in C#, …) It is very easy to create stand-in objects for lowering memory pressure. It is very easy to write an ORIM. Shall I continue?
B: Yes
A: Is is that flexible that you can write a whole AOP framework within that language. It is that flexible that you can write a prototype based framework within that language.
However, sometimes it is easy to detect for the compiler that something makes no sense at all. And sometimes the compiler warns about that. But in many cases the compiler is not more intelligent than the developer.
Agreed that it should generate a warning, but it doesn't. Part of the issue is that all ObjC objects are id at runtime, which is why you're seeing different behavior for int (which isn't id). But that's not really an excuse. It's a limitation of the compiler. There are numerous places where it doesn't do a good job of distinguishing between ObjC object types. ObjC objects are duck-typed, so as long as they respond to the right messages "they work."
Sometimes this is a benefit; for example, NSArray is actually a class cluster, and there are several (private) types that pretend to be NSArray by just implementing the same interface. That's something that is easy in ObjC, but hard in Swift. Still no excuse, since it would be easy to get that benefit without this frustrating lack of a compiler warning, but it gets back to how ObjC thinks about class types.
This limitation is fixed in Swift, and another benefit of moving over, but that doesn't really help you, I know.

Objective-C Blocks in C

While reading through the blocks conceptual overview in Apple Docs, I saw the following statement:
Although blocks are available to pure C and C++, a block is also
always an Objective-C object.
How is this possible? I mean an Objective-C object available in pure C. I'm getting confused.
How is this possible? I mean an Objective-C object available in pure C.
Matt Gallagher wrote an article that nicely explains how blocks work. In a nutshell, blocks are defined as structs that meet the requirements to be a valid Objective-C object (for example, the struct starts with an isa pointer). None of this causes a problem for C, and the compiler knows what the definition of a block is, so even when compiling plain old C it can still do the right thing to make blocks work.
The added Objective-C aspect of blocks doesn't affect how blocks are used in C, but still provides the ability to treat blocks as objects so that they can be added to collections and otherwise managed like any other object.
This isn't really so strange. If you think about it, all Objective-C objects are "available" in C at some level -- the entire Objective-C runtime consists of C functions that manipulate structures that represent Objective-C objects and classes. And even disregarding that, blocks aren't the first example of a data type that's usable in both C and Objective-C -- we've had toll free bridging between Foundation and Core Foundation for many years. The implementation of blocks may be somewhat different, but it's not a new thing to have objects that work in both worlds.
Objective-C can be freely mixed with C. As long as your class has a C API (which blocks do, with Block_copy, Block_release, etc.), the C code doesn't care if it's implemented in Objective-C or C.
From the same document,
float (^oneFrom)(float);
oneFrom = ^(float aFloat) {
float result = aFloat - 1.0;
return result;
};
oneFrom a variable referencing the block (object) { float result = aFloat - 1.0; return result; }
Blocks are available to pure C and C++, ie. the block can consist of pure C or C++ code.

Is Objective-C converted to C code before compilation?

I know objective C is strict superset of C and we are writing the same thing.
But when i write
#interface Myintf {}
#end
Does it get converted to a C struct or is it that the memory layout for the data structure Myintf prepared by Objective c compiler is same as that of a C struct defined in runtime.h?
and same question about objc_msgsend
Apple document says
In Objective-C, messages aren’t bound to method implementations until runtime. The compiler converts a message expression, into a call on a messaging function, objc_msgSend. This function takes the receiver and the name of the method mentioned in the message—that is, the method selector—as its two principal parameters:
Does it get converted to a C struct
In the old days it used to, but with the modern runtime (OS X 10.5+ 64 bit and iOS), I think it's a bit more complicated. It can't be using a traditional struct because the Fragile Instance Variable problem is solved.
and same question about objc_msgsend
Yes. All method invocations - or more correctly, all message sends - are converted into calls to obj_msgsend() (except for when super is used as the receiver when a different C function is used).
Note that early implementations of Objective-C were implemented as a preprocessor and produced C source code as an intermediate step. The modern compiler does not bother with this and goes straight from Objective-C source code to an object code format.
No and no. Both cases ultimately rely on the runtime. In a way, it is converted to use C interfaces, but there is a level of abstraction introduced -- it's not entirely static.
It will help to look at the assembly generated by the compiler to see how this works in more detail.
Given the declaration:
id objc_msgSend(id theReceiver, SEL theSelector, ...);
The compiler inserts a call to objc_msgSend when your implementation calls a method. It is not reduced to a static C function call, but dynamic dispatch -- another level of indirection, if you like to think of it that way.

Template in Objective C?

Everything is in the title :)
Is there any templates in ObjC ?
I need equivalent of c# :
public class MyClass<T> : Message
in ObjC .
Any helps will be strongly thanks :(
There is no such ObjC feature. While ObjC++ does exist, I strongly discourage its broad use. It has many problems from poor tool and debugger support, to poor compiler optimization, to degraded ARC performance.
Generally templates are not required in ObjC because it is not a strongly typed language. An NSArray can hold any object, so you don't need to use a template to get the right type. Do you have a specific problem you're trying to solve? There is likely a better ObjC solution.
Obj-C supports templates since Xcode v7. It is named generics:
Lightweight generics now allow you to specify type information for
collection classes such as NSArray, NSSet, and NSDictionary. The type
information improves Swift access when you bridge from Objective-C,
and simplifies the code you have to write. For example:
NSArray<UIImage *> *images;
NSDictionary<NSString *, NSURL *> *resourcesByName;
Look for "Objective-C Language Changes" section in
https://developer.apple.com/library/content/documentation/Xcode/Conceptual/RN-Xcode-Archive/Chapters/xc7_release_notes.html
By the way, Xcode supports adding C++ classes through the New->File. Using the extern "C" {} construct in C++ means you can provide as much or as little C-callable interface as you need, which you can then call directly from your Objective-C code, since Objective-C is a superset of C.
Having said that, it's probably a good idea to stick within the Objective-C paradigm unless you have a pressing reason to move outside it, such as the need to incorporate a body of existing C++ code into your project. (That's not to say that Objective-C is a "better" language, which is a different matter entirely.)

How to code a method, function or variable in Objective - C

I have just started to learn Objective - C. I have done one year of Java programming and one year of Actionscript. I need to find a website or blog which tells me how to do the basic things for example declare a variable or how to write a method and function. I cant seem to find this anywhere. If someone could give me some good links that would be great.
Thanks
Introduction to The Objective-C 2.0 Programming Language from Apple would probably be a good place to get started with the Objective-C language.
In general, declaring variables aren't too different within a method.
-(void)doSomething {
// Declaration of a variable.
int myVariable = 0;
}
The syntax for methods and functions can be a little bit different, and the language itself allows the use of C, as Objective-C is a superset of C.
One conceptual difference about classes and objects in Objective-C compared to Java is that the implementation and the declaration is separated into two different files. The "header" information which defines the interface is usually included in the .h file, while the implementation is included in the .m file.
The interface defines the methods, properties and such, while the implementation includes the actual code to use in the methods.
Also, strictly speaking, in Objective-C are not "methods" are not "called", but "messages" are "sent" to objects, and the objects react to them:
// The following is sending the "doSomething" message to "myObject".
// Strictly speaking, it's not a method call, but a messaging of an object.
[myObject doSomething];
Also, the Wikipedia article on Objective-C also gives a pretty good overview of the language as well.
I would highly recommend the book Programming in Objective-C 2.0 by Stephen Kochan.
I used the older version when I was learning Objective-C and still reference it on occasion. It is an excellent introduction to the basics of the language.