What is 'id' in the following code? in Objective C [closed] - objective-c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to ask that what is that id? I don't understand what this id is. I got this code from a book and it says a generic type that's used to refer to any kind of object. Can anyone help me with this? I read it few times. Still can't get it.
void drawShapes (id shapes[], int count){
for (int i = 0; i < count; i++) {
id shape = shapes[i];
[shape draw];
}
} // drawShapes

id is an alias for an unknown Objective-C object. It can be used to declare any Objective-C object value.
In the example you have it is using an id rather than a specific class so that the code is not dependent on the class of shape.

Strictly speaking id is defined as a pointer to an objc_object struct.
typedef struct objc_object {
Class isa;
} *id;
In practical terms this means any Objective-C object.
However don't confuse this with NSObject *. While in many cases the equivalence may hold, there are classes which do not descend from NSObject but are still valid Objective-C objects (and therefore whose type can be id). One notable example is NSProxy.

In the code you posted, the id stands for the type of items that will be stored in a C static Array. In particular, the id type indicates any Objective-C object.
Anyway, I would not recommend to use C static arrays in Objective-C to contains objects of unknown type, when you can achieve the same result by using an instance of NSArray.

id means "a reference to some random Objective-C object of unknown class" an example is when you make an at property for a uibutton sometimes it will come up as id but setting it as uibutton will help xcode fill in blanks for you while your typing because now xcode knows exactly what this object is. in your situation shape could be a string or a number or something else if you were just looking at that line of code though passing anything into it could give another line a error later on.

Related

How can I get sizeof class based on NSObject [duplicate]

This question already has answers here:
Checking the size of an object in Objective-C
(6 answers)
Closed 8 years ago.
I'm new to obj-c . During these day's practices I noticed that every class based on NSObject can't have an entity like : NSObject en; in c++ but NSObject* en instead.
But, sometimes I need to know the Size of an Object.I can't simply write sizeof(en) because en is a pointer var.I can't simply use sizeof(NSObject) neither for the compiler telling me Application of sizeof to interface 'XXXX' is not supported on this architecture and platform.
I want to know if there is a way to get sizeof(NSObject) .If not,what the syntax is designed this for & any other ways to get the size.
From doc
class_getInstanceSize
Returns the size of instances of a class.
size_t class_getInstanceSize(Class cls)
Parameters cls A class object.
Return Value The size in bytes of instances of the class cls, or 0 if
cls is Nil.
But I doubt this is what you really want. Because I never found it useful and can't think a case it may be useful. (other than learning memory layout of objects and low level implementation details)
First, you should import malloc.h
If you use Non-ARC:
malloc_size(myObject);
if you are using ARC:
malloc_size((__bridge const void *) myObject));
This linker is a question similar to yours.

Dereferencing an uninitialized pointer in Objective-C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is happening in this code http://ideone.com/stD7VU
First I thought ok i'm using an int for a pointer and the compiler doesn't warn me. Then the 2nd block I can't understand how I can dereference a when I didnt use new. Whats happening? I don't know obj-c.
#import <stdio.h>
#implementation TestObj
int main()
{
{
int *a;
a=5;
printf("%d\n", a);
}
{
int *a;
*a=7;
printf("%d\n", *a);
}
return 0;
}
#end
First I thought ok i'm using an int for a pointer and the compiler doesn't warn me.
Actually it does. In the first block, the line
a=5;
will rise a compiler warning, specifically
Incompatible integer to pointer conversion assigning 'int *' from 'int'.
I can't understand how I can dereference a when I didnt use new
You are trying to dereference an uninitialized pointer. This is undefined behavior in C (and being Objective-C a superset of C, so it's in it), so you program could technically print the whole Divine Comedy by Dante and still be consistent with the specification.
By the way you don't need any special C construct for initializing pointers. Objective-C is a proper subset of C, so you can use malloc.
In case of objects there's a whole set of APIs dedicated to object allocation and deallocation, including new.

How to implement methods found in the Mac Developer Library [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm a totally new to Objective C programming and just need to check how would I implement something I find on the Mac Developer Library.
For example I found this code in the Mac Developer Library:
- (BOOL)containsObject:(id)anObject
Are the steps I need to implement this method?
in the .h file add
-(BOOL)containsObject:(id)anObject;
then in the .m file implement it like this;
- (BOOL)containsObject:(id)anObject
{
//What do I place here to search my array with the objects?
return YES;
}
Can someone help me with an example how I would search an array of numbers and use this method?
This is my array:
NSArray *first;
first = [NSArray arrayWithObjects:1,2,3,4,5, nil];
Do you mean "implement" - as in write your own version - or "use"? You seem to start with the former and end with the latter...
How do you use it? Well taking your example, corrected:
NSArray *first = [NSArray arrayWithObjects:#1, #2, #3, #4,# 5, nil];
The #1 etc. is a shorthand to create an NSNumber object - you can only put object references and not primitive values into an NSArray. The shorthand effectively expands to [NSNumber numberWithInt:1] etc.
Now to use containsObject::
BOOL containsTheAnswerToEverything = [first containsObject:#42];
This will set the BOOL variable to YES if the array contains an NSNumber representing 42, and NO otherwise.
How do you implement it? You examine each element of your array in a loop comparing each to the object you are looking for, same algorithm you would use in C (which it seems you know).
If you are asking how to define a class, then you should read up on Objective-C, but your point 2 is the correct outline.
HTH
In respect to the first question, you can do just that. An example to give you a better visual understanding would be this:
YourClassName.h
#import <Foundation/Foundation.h>
#interface YourClassName : Subclass //replace subclass with something like NSObject or whatever you need
{
}
- (BOOL)containsObject:(id)anObject;
#end
and...
YourClassName.m
#import "YourClassName.h"
#implementation YourClassName
- (BOOL)containsObject:(id)anObject
{
//Insert function body here
}
#end
As for your second question, I am not really very familiar with using NSArray or loading it using that strange function. My advice would be using (NSArray)anObject instead of (id)anObject as you can load the array directly into your function and create your search parameters there. I'm not sure exactly what object you are looking for in terms of containsObject. Are you seeing if it contains the number? If the value contains the array? specify it a bit and I may be able to dig up a better answer for you
EDIT:
It occurred to me that you are probably just looking for the number inside of the array seeing as you are newer to Objective-C. To accomplish what you want you have a couple options. Both require the change of your function. The first would be just changing the function to this:
- (BOOL)containsObject:(int)object fromArray:(int*)array length:(int)length;
In YourClassName.h. Now you can always change your parameters to different data types but this will work for your integers. You can also do this without the length parameter but I figure it saves us some code (personal preference). And in the .m file:
- (BOOL)containsObject;(int)object fromArray:(int*)array length:(int)length
{
for(int i = 0; i <= length; i++)
{
if (array[i] == object)
{
return YES;
}
}
return NO;
}
second would be just without the length option and a bit more code

Is there any way to get a property's type in Objective-C? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to detect a property return type in Objective-C
Is there any way to get a property's type in Objective-C? I can access the property like this:
objc_property_t* properties = class_copyPropertyList(cl, &count);
And get the name like this:
property_getName(properties[i]);
What I need to do though is get the type. Also, the value will be nil in most cases so I can't just get the value calling object_getClass().
Not in the sense that you seem to be asking — in Objective-C classes are typeless; when dealing with non-C types beyond 'it's a class' the type of properties isn't known at runtime. That's why if you do something silly like the following in a view controller:
[self setValue:#3 forKey:#"view"];
You'll see an exception raised when the controller attempts to send a view message to the NSNumber rather than by the key-value coding mechanisms because you tried to put something that isn't a view into in an inappropriate property.
Parsing property_getAttributes will allow you to go no further than distinguishing the various C literal types from an Objective-C object type.

Is there an Ultimate Guide to Pointers in Objective-C? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
Ok... I understand what pointers are and how they point to a memory location where the variable is stored.
However, I still can't fully get my head wrapped around when the pointer (asterisk) is to be used and when it isn't. It's still seemingly random to me.
Does anyone have any recommendations for good tutorials on the web or book chapters that really go into detail on pointers?
Thanks!
Edit: What I'm really looking for is a detailed guide that is specific to Objective-C either in a deep website tutorial or book chapter(s). I don't think there is enough space here to fully explain it for me.
Being aware that this is tagged as Objective-C..
Take a look at here.
(Un)fortunately, the asterisk * has many different meanings depending on context. So, let's look at the relevant ones. Let us write T for some arbitrary type (say int):
T x; // variable of type x, stored somewhere in memory
T * pt; // a pointer to a variable of type x -- doesn't have a value just yet
pt = &x; // the value of pt is now the address of the variable x
So far so good. We have used the asterisk to designate a new type, namely T*, which is a "pointer to T".
But what do we do with a pointer? We can dereference it to get to the value of the variable at the address pointed to by the pointer:
T y; // another variable of type T
y = *pt; // equivalent to y = x;
*pt = 81; // equivalent to x = 81;
So, if the asterisk is part of the typename, then it designates a pointer type. If it comes before a variable name (which is itself of pointer type), then it dereferences the pointer.
[Clarification:] In C, pointers naturally go hand-in-hand with the "address-of" operator &, which is used to actually obtain a pointer to something. In Obj-C, a pointer is obtained as the result of object allocation (+ initailization): T * pt = [T new];
Beware that Obj-C offers an alternative syntax to the traditional C and C++ pointer syntax, so you may encounter pointers in other guises.[/Clarification]
(The asterisk can also be used as a binary operator of course, so you can have something like this: int x = 5; int * p = &x; int y = *p * *p;.)
Peter Hosey of Growl and Adium has posted a guide to pointers on his blog. He calls it, "Everything you need to know about pointers in C," but that's because he regards the ugly pointer aspects as belonging to C rather than Obj-C. Check it out.
I don't know of any reference beyond the Clang ARC reference that describes all the crazy modifiers you can now put on pointers in Obj-C, though. And that's not a good learning resource if you're already confused.
Assuming that C pointers have no secret to you, basically in Objective-C there are two caveats to avoid:
The NS- prefix does not always denote a class. Sometimes this is only a typedef. You have to check the reference manuals.
Dotted notation introduced in Objective-C 2.0. Despite the fact that every object is a pointer, sometimes instance variables can be accessed by myObj.myVar, instead of (more consistent for newcomers) myObj->myVar.
The ultimate guide to pointers is in Kernighan & Ritchie. They're the same in Objective-C as they are in C.