Why is there no way to do introspection in Objective C with Objects? - objective-c

I have seen examples (on here especially) of calling hideous C functions and getting structures back that have to be iterated, replete with reams of underbars.
Why can't I do this (pseudo to follow):
Money *cost = [[Money alloc] init];
for (Property *property in [[cost class] properties]){
..
}
for (Method *method in [[cost class] methods]){
..
}
?

Those functions are not hideous. They are all documented in the Objective-C Runtime Reference.
One reason I think there aren't the +properties and +methods methods are because it's rare you need to look for property/method that you don't know the name in compile time.
The most useful introspection functions in ObjC are -respondsToSelector:, -isKindOfClass:, -conformsToProtocol:, NSInvocation, KVC, KVO, NSXxxxFromString, and they are operating with objects.

Here's why you can't do it: Because Cocoa operates on a level above the runtime. The Objective-C runtime functions can't reasonably depend on Cocoa, an optional library implemented on top of it. It would be possible to create an object-oriented layer on top of the runtime API, but this was not a design goal of Cocoa. It's just not necessary to do what Cocoa does.

Check out NSClassDescription and the cover methods on NSObject. This may be close to what you are looking for.

Related

Can Swift do everything that Objective-C can do?

I am new to IOS developing, and want to use the Swift language instead of Objective-C.
I know few concepts about Cocoa touch, and I want to know : Can Swift do everything that Objective-C can do ?
There are a lot of things that can be done in Objective-C but cannot be done in Swift, without implementing it in Objective-C and then using it from Swift. Some of them include:
Catching Objective-C exceptions
Using C++ APIs (through Objective-C++)
Using NSInvocation, performSelector: and other ways of making calls dynamically where the method to call is chosen at runtime
Handling unimplemented method calls using forwardInvocation:
Provide a function for use in C APIs that take a function pointer
The only concept I know that is in Objective-C but not in Swift, is Key-Value Observing (KVO). You can use KVO for a Swift class to observe the property of an Objective-C class, but you cannot observe any arbitrary property of a Swift class. See this answer for more details.
This is an interesting question but essentially the answer must be NO because you can use Objective-C resources in swift using bridging-headers. Xcode automatically translates Swift to Objective-C and vice versa. However, if you cannot write Objective-C code then you cannot include your own custom objective-c classes in your swift projects!
It all depends on how you like to code. Apple have said that Objective-C is still a 'first class' language meaning that they are going to run Swift and Objective-C side by side for the foreseeable future. Personally I prefer Objective-C because you can use C very easily (as anything that is legal in C is also legal in Objective-C) added to which Swift is a more procedural in style where Objective-C is quite clearly object orientated.
It is worth noting that the Cocoa and Cocoa Touch classes are all objective-c classes and so it may be useful to have a working knowledge of Objective-C. I think the best advice I've heard so far is, if you have the time, learn both!

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.)

What is the definition of Convenience Method in regards to Objective C?

In most languages I have dealt with, one something is called a convenience method, it means that the method does some small task that gets done very frequently, and therefore it is more convenient to use said method.
In Objective-C does this definition hold true? Or is it generally only used to describe class methods that return a prebuilt object? ex. [NSString stringWithContentsOfFile:...]
Is this just a preference thing, or are there some hard and fast definition for these terms?
Cheers,
Stefan
What you are talking about is actually more specifically a "convenience constructor" in Objective C. (Note that it's not really a constructor in the C++/Java/C# sense, it's actually an object initializer/factory method, but it seems to be the convention to call the "convenience constructors"). "Convenience constructors" in Obj C are a convention or pattern for creating a constructor/initializer/factory method for a class which takes specific parameters. This pattern also has some special conventions that you should follow (such as autoreleasing the new object within the constructor), so that your custom classes fit in well with the built-in types.
See this page (a little way down) for more info: http://macdevcenter.com/pub/a/mac/2001/07/27/cocoa.html?page=3
As for "convenience method," this specific term doesn't have any special meaning in Objective C. You can create any type of convenience method in Obj C, and there is no expectation about what it should or should not do. It's only "convenience constructor" that has a special meaning.
So far as I know, "convenience method" means basically what you defined it to mean here: a single method or function which replaces a more complicated series of invocations because of its frequency of use.
In Objective-C, the "ordinary" way to create a new instance is something along the lines of NSSomething * mySomething = [[[NSSomething alloc] initWithParam:... andParam:...] autorelease]. Many classes provide convenience constructors which simplify these three steps (in fact, in most cases, they probably literally do exactly the same thing, but wrapped behind a class method call).

C function vs. Objective-C method?

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.
In Objective-C each function operates on an object, like
[myObject myFunction]
A C method has the form:
return-type function-name(argument1, argument2, etc) {}
An Objective-C instance method has the form:
-(return-type)function-name:argument1 {}
or for a multi-argument function
-(return-type)function-name:argument1 function-name:argument2 {}
I always use Objective-C-style methods in Obj-C programming, even though you can still use C-type functions as well.
I suppose the equivalent in C to [myObject myMethod:arg] might be myObject.myMethod(arg)
The first is a freestanding function. The second is an instance method for an Objective-C class. So I guess you would need the second version if you're actually writing a class.

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.