concept of object from c/python to object-c - objective-c

I have experience on C and Python,
I learned the Object-C today,
I want to make sure if my concept is correct ?
I don't know why should I put a statement in a bracket
[pt setX: 8];
Isn't pt setX: 8 meaningful enough ?
If brackets is only for readable, why I got errors in this picture,
I just want to know when should I use the bracket , and when isn't need.
Is pt setX: 8 similar to pt.setX(8) in Python or C-like language?
To create a object,
You have to define .h .m,
In C, you can define and implement both in a .c file , but can not in object-c ?
If you want autorelease the object memory without explicitly free the memory in manual,
Just put your code in the #autoreleasepool block, right ?
#autoreleasepool {
MyPoint* pt = [MyPoint alloc];
// call constructor
pt = [pt init];
[pt print];
[pt getArea];
[pt setX: 8];
[pt setY: 99];
[pt print];
[pt getArea];
}
MyPoint.m
//
// MyPoint.m
// hello_world
//
// Created by poc on 2014/4/27.
// Copyright (c) 2014年 poc. All rights reserved.
//
import "MyPoint.h"
#implementation MyPoint
- (void) print
{
NSLog(#"X =%i and Y= %i", _x, _y);
}
- (void) getArea
{
NSLog(#"Area is %i", _x*_y);
}
- (void) setX:(int)aX
{
_x = aX;
}
- (int) getX
{
return _x;
}
- (void) setY:(int)aY
{
_y = aY;
}
- (int) getY
{
return _y;
}
#end

Is pt setX: 8 not meaningful enough ?
No, it's not. Let's assume situation when you want use result of method invocation as object
pt area intValue // without brackets it's a mess
[[pt area] intValue]; // looks readable now
Is pt setX: 8 similar to pt.setX(8) in Python or C-like language?
Yes, it similar. But you need square brackets
In C, you can define and implement both in a .c file , but can not in object-c ?
Analog of .c file for obj-c is named .m. There you can do the same stuff as you can in .c, importing of .m is really bad practice, it leads you in majority of cases to incorrect linking and, eventually in failure of build. Also it good way to separate private and public interfaces. .h contains public interface to class, you import .h and see only public methods and class variables, while .m contains private methods and variable that you don't want to expose.
If you want autorelease the object memory without explicitly free the memory in manual,
Just put your code in the #autoreleasepool block, right ?
No, it's not. You can't count on autoreleasing of variables you puts there. Autorelease pool created for another purpose. If you want to know why - read this.
I encourage you to use ARC (automatic reference counting), it's enabled by default in latest project templates in Xcode. This way you don't need to worry about memory management, while you correctly use naming convention.

I don't know why should I put a statement in a bracket
That's just the syntax for method calls. Why are parentheses required around arguments in C and Python? Syntax. Other languages don't require parentheses or brackets for method and function calls (e.g. Smalltalk, Ruby and Perl, though parentheses allow you to be more expressive) because they use different syntax. Smalltalk, in particular, is similar to Objective-C method calls, but without the brackets (not coincidentally, since Smalltalk inspired Objective-C).
Is pt setX: 8 similar to pt.setX(8) in Python or C-like language?
Yes. In particular, [pt setX: 8] calls method setX on (or, if you prefer, sends message setX to) object pt, passing 8 as a parameter.
In C, you can define and implement both in a .c file , but can not in object-c ?
Keep in mind that anything declared solely in a compilation unit (a ".c" file) isn't accessible in other compilation units. With Objective-C, you can declare both static variables (as you might in C) and methods in a compilation unit (which have that ".m" extension), but they are effectively private.
If you want autorelease the object memory without explicitly free the memory in manual, [j]ust put your code in the #autoreleasepool block, right ?
An #autoreleasepool block isn't responsible for keeping track of object lifetime; see "Why is autorelease (#autoreleasepool) still needed with ARC?" for what it does. See also "Transitioning to ARC Release Notes" for info on Automatic Reference Counting (ARC) and "Memory management" for info on the older approach (manual reference counting), which is what ARC does under the hood.

Related

#autoreleasepool with no foundation or corefoundation (libobjc only)

NOTE: All references to libobjc are referring to Apple's runtime. I'll deal with the GNU runtime later.
I'm trying to get a handle on what exactly #autoreleasepool does at runtime so that I can use it in my foundation-less framework.
I've been able to hook into #(#), #[] and #{} to return instances of my number, array and dictionary classes — all derived from my root class and easier to hack as all the plumbing happens in objc — but #autoreleasepool seems to be handled differently by the compiler.
Rather than just injecting calls to [[NSAutoreleasePool alloc] init] and [pool release] which I could maybe swizzle in the objc layer, the compiler injects calls to two private C functions in the runtime: objc_autoreleasePoolPush() and objc_autoreleasePoolPop()... and for whatever reason, those C functions do not in turn call [[NSAutoreleasePool alloc] init] and [pool release].
I had previously thought that calling objc_autoreleasePoolPush() was actually creating a new pool and pushing it onto the pool stack, but the return value is 0x01, which is maybe some sort of sentinel/placeholder value — it's definitely not an instance of NSAutoreleasePool.
Anyway, what I need is to either:
A: intercept allocation/initialization/deallocation of NSAutoreleasePools injected during compilation of #autoreleasepool so that I can alloc/init/dealloc instances of my own autorelease pool class
or
B: implement a separate, post-compilation binary patching step that overwrites calls to these C functions with calls to my own corresponding function addresses
Any ideas on either of these options?
...those C functions do not in turn call [[NSAutoreleasePool alloc] init] and [pool release].
A decent part of Objective-C runtime library was re-written in C++ in the latest versions, the autorelease pool block is not an exception - the use of NSAutoreleasePool was completely replaced with the functions you found, which under the hood call static methods of AutoreleasePoolPage C++ class. It means that nowadays #autorelease has nothing to do with NSAutoreleasePool apart from common past.
I had previously thought that calling objc_autoreleasePoolPush() was actually creating a new pool and pushing it onto the pool stack, but the return value is 0x01...
According to the clang documentation objc_autoreleasePoolPush() returns an opaque “handle” to a new autorelease pool. An "opaque handle" in this case is just a void pointer to an actual autorelease object (which is not an instance of NSAutoreleasePool in this case), so you don't have any access to its interface (but you can later use it to pass as an argument to other functions of the same section).
what I need is to either:
A: intercept allocation/initialization/deallocation of NSAutoreleasePools injected during compilation of #autoreleasepool so that I can alloc/init/dealloc instances of my own autorelease pool class
The only way to enforce use of NSAutoreleasePool by #autoreleasepool block is to compile the Objective-C code with legacy runtime (macosx-10.6 or earlier).
or
B: implement a separate, post-compilation binary patching step that overwrites calls to these C functions with calls to my own corresponding function addresses
I'm not an expert with that, but it seems to be the only viable option if you want to inject your own functionality in place of #autoreleasepool blocks.
However for debugging purposes you may get use of how clang handles undefined behaviour scenario with ODR violations for C functions (it doesn't fail at linking step, but which function gets called is not certain). You surely should not use such a code for any serious project.
#import ObjectiveC;
#include <stdio.h>
#pragma mark Autorelease functions
void *objc_autoreleasePoolPush(void) {
printf("AR New init\n");
static void *handle = &handle;
return handle;
}
void objc_autoreleasePoolPop(void *handle) {
printf("AR New drain\n");
}
#pragma mark Autorelease object
#interface NSAutoreleasePool : NSObject
- (void)drain;
#end
#implementation NSAutoreleasePool
- (instancetype)init {
if (self = [super init]) {
printf("AR Old init\n");
}
return self;
}
- (void)drain {
printf("AR Old drain\n");
}
#end
#pragma mark Main
int main(int argc, const char * argv[]) {
#autoreleasepool {
NSObject *object = [[NSObject new] autorelease];
}
return 0;
}
To summarise, if you run this code with some legacy runtime, it will use the custom NSAutoreleasePool in place of #autoreleasepool:
% clang -ObjC -fmodules -lobjc -fobjc-runtime=macosx-10.6 -o main main.m
% ./main
AR Old init
AR Old drain
With the latest runtime, the program will use the redefined functions (again, this is just for demo purposes, avoid using such an approach in your code):
% clang -ObjC -fmodules -lobjc -o main main.m
% ./main
AR New init
AR New drain
EDIT
For the ODR part, I actually was convinced that upon linking lld may end up with undefined behaviour, since two symbols with the same name exist in a program, however after digging a little deeper into the question, it looks like the rules are well-defined (at least for llvm linker):
SymbolTable
SymbolTable is basically a hash table from strings to Symbols with
logic to resolve symbol conflicts. It resolves conflicts by symbol
type.
If we add Defined and Undefined symbols, the symbol table will keep the former.
If we add Defined and Lazy symbols, it will keep the former.
If we add Lazy and Undefined, it will keep the former, but it will also trigger the Lazy symbol to load the archive member to
actually resolve the symbol.
Whether it's reliable outside of macOS / llvm ecosystem is way beyond my expertise

Using objc_msgSendSuper to invoke a class method

I was going through and replacing #synthesized(self) locks w/ this method
void _ThreadsafeInit(Class theClassToInit, void *volatile *theVariableItLivesIn, void(^InitBlock)(void))
{
//this is what super does :X
struct objc_super mySuper = {
.receiver = (id)theClassToInit,
.super_class = class_getSuperclass(theClassToInit)
};
id (*objc_superAllocTyped)(struct objc_super *, SEL, NSZone *) = (void *)&objc_msgSendSuper;
// id (*objc_superAllocTyped)(id objc_super, SEL, NSZone *) = (void *)&objc_msgSend;
do {
id temp = [(*objc_superAllocTyped)(&mySuper /*theClassToInit*/, #selector(allocWithZone:), NULL) init];//get superclass in case alloc is blocked in this class;
if(OSAtomicCompareAndSwapPtrBarrier(0x0, temp, theVariableItLivesIn)) { //atomic operation forces synchronization
if( InitBlock != NULL ) {
InitBlock(); //only the thread that succesfully set sharedInstance pointer gets here
}
break;
}
else
{
[temp release]; //any thread that fails to set sharedInstance needs to clean up after itself
}
} while (*theVariableItLivesIn == NULL);
}
which while a bit more verbose exhibits significantly better performance in non-contested cases
along with this little macro (excuse poor formatting, it's very simple). To allow the block to be declared after the initial nil check, looks to help LLVM keep the "already initialized" path extremely fast. That's the only one I care about.
#define ThreadsafeFastInit(theClassToInit, theVariableToStoreItIn, aVoidBlockToRunAfterInit) if( theVariableToStoreItIn == nil) { _ThreadsafeInitWithBlock(theClassToInit, (void *)&theVariableToStoreItIn, aVoidBlockToRunAfterInit); }
So initially implemented it using the commented out sections for objc_superAllocTyped (actually first using [theClassToInit allocWithZone:NULL], which was definitely the best approach :) ), which worked great until I realized that most of the singletons in the project had overridden allocWithZone to return the singleton method... infinite loop. So I figured using objc_msgSendSuper should sort it out quickly, but I get this error.
[51431:17c03] +[DataUtils allocWithZone:]: unrecognized selector sent to class 0x4f9584
The error doesn't seem to be related to the actual problem, as...
(lldb) po 0x4f9584
$1 = 5215620 DataUtils
(lldb) print (BOOL)[$1 respondsToSelector:#selector(allocWithZone:)]
(BOOL) $2 = YES
So I'm definitely missing something... I compared to assembly generated by a [super allocWithZone:NULL] method in an empty class... almost identical except for the functions called have different names (maybe just using different symbols, no idea, can't read it that well).
Any ideas? I can use class_getClassMethod on the superclass and call the IMP directly, but I'm trying to be reasonable in my abuse of the runtime :)
Alright, this wasn't actually that tricky once I recalled that the meta class contains all of the method information for a Class instance obtained via -[self class] or +[self] -> thanks http://www.cocoawithlove.com/2010/01/what-is-meta-class-in-objective-c.html
This error occurred because I was asking the runtime to look up the method in NSObject's set of instance methods, which obviously doesn't contain allocWithZone: . The mistake in the error log presumably originated because the receiver was a metaclass instance, and Apple has their interns implement error logs.
so while with a normal instance method call via objc_msgSendSuper, you would pass a metaclass instance as objc_super.super_class, to invoke a class method, the metaclass itself is needed (everything is one level up).
Example, and a diagram that helped me understand this - (http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html)
struct objc_super mySuper;
mySuper.receiver = theClassToInit; //this is our receiver, no doubt about it
//either grab the super class and get its metaclass
mySuper.super_class = object_getClass( class_getSuperclass( theClassToInit ) );
//or grab the metaclass, and get its super class, this is the exact same object
mySuper.super_class = class_getSuperclass( object_getClass( theClassToInit ) );
Then the message can be resolved correctly. Makes perfect sense now that I started paying attention :P
Anyways, now that I found my mistake I feel like I've leveled up my Objc runtime understanding. I was also able to fix an architectural mistake made two years ago by someone I never met without having to modifying and re-test dozens of classes across 3 projects and 2 static libraries (God I love Objective-C). Replacing the #synchronized construct with a simple function call also halved the compiled code size of those methods. As a bonus, all our singleton accessors are now (more) threadsafe, because the performance cost for doing so is now negligible. Methods which naively re-fetched the singleton object multiple times (or in loops) have seen a huge speedup now that they don't have to acquire and release a mutex multiple times per invocation. All in all I'm very happy it all worked as I'd hoped.
I made a "normal" Objective-C method for this on a category of NSObject, which will work for both instance and Class objects to allow you to invoke a superclass's implementation of a message externally. Warning: This is only for fun, or unit tests, or swizzled methods, or maybe a really cool game.
#implementation NSObject (Convenience)
-(id)performSelector:(SEL)selector asClass:(Class)class
{
struct objc_super mySuper = {
.receiver = self,
.super_class = class_isMetaClass(object_getClass(self)) //check if we are an instance or Class
? object_getClass(class) //if we are a Class, we need to send our metaclass (our Class's Class)
: class //if we are an instance, we need to send our Class (which we already have)
};
id (*objc_superAllocTyped)(struct objc_super *, SEL) = (void *)&objc_msgSendSuper; //cast our pointer so the compiler can sort out the ABI
return (*objc_superAllocTyped)(&mySuper, selector);
}
so
[self performSelector:#selector(dealloc) asClass:[self superclass]];
would be equivalent to
[super dealloc];
Carry on runtime explorers! Don't let the naysayers drag you into their land of handwaving and black magik boxes, it's hard to make uncompromisingly awesome programs there*.
*Please enjoy the Objective-C runtime responsibly. Consult with your QA team for any bugs lasting more than four hours.

Call objective c++ method from objective c

I'm just learning Objective C (and objective-c++ for that matter) and I have an Objective-C++ class with the following constructor.
void InputManager::_init (int inputAreaX, int inputAreaY, int inputAreaWidth, int inputAreaHeight)
How do I invoke this from objective C?
This appears to be a pure C++ method so it would work exactly the same as in ordinary C++ (even in an Objective-C++ file). For instance you might have defined a variable on the stack:
InputManager mgr; // or, include constructor arguments if the class can't be default-constructed
mgr._init(x, y, w, h); // this assumes 4 variables exist with these names; use whatever parameter values you want
The name _init is a bit weird though; do you mean for this to be a constructor for the class? If so, InputManager::InputManager(int x, int y, int w, int h) should probably be defined instead.
If you actually want this class to be Objective-C only, the syntax and behavior are different.
You have two options:
Option 1.
Translate it into Objective-C only code. I'm not so good with C++, but this might be what it looks like in the .h:
-(id)initWithAreaX: (int) inputAreaX AreaY: (int) inputAreaY AreaWidth: (int) inputAreaWidth AreaHeight: (int) inputAreaHeight;
Since it looks like that's a constructor method, it would probably look like this in the implementation:
-(id)initWithAreaX: (int) inputAreaX AreaY: (int) inputAreaY AreaWidth: (int) inputAreaWidth AreaHeight: (int) inputAreaHeight {
self = [super init];
if(self) {
//Custom Initialization Code Here
_inputAreaX = inputAreaX;
_inputAreaY = inputAreaY;
_inputAreaWidth = inputAreaWidth;
_inputAreaHeight = inputAreaHeight;
}
return self;
}
And you might call it like this:
InputManager *object = [[InputManager alloc] initWithAreaX: 20 AreaY: 20 AreaWidth: 25 AreaHeight: 25];
Option 2.
The whole purpose of Objective-C++ is to allow the developer to integrate C++ and Objective-C code. You want to know how to call an Objective-C++ method from Objective-C, but the entire purpose of Objective-C++ is to integrate the two, so there's no point to trying to find a loophole to call an Objective-C++ method in a file that is otherwise completely Objective-C. So the second option is to just make the file that you want to call the Objective-C++ method in an Objective-C++ file with a ".mm" extension.
Hope this helps!

Where is the retain count stored for NSObjects in Objective C

I am curious about how retain/release work internally. On the face, it seems like there's an integer related to each instance of an NSObject, which gets increased and decreased when you call -retain and -release, respectively.
But taking a look at NSObject, the only instance variable it has is the isa variable, for determining its class type.
So where are retain counts for individual objects stored? Not that I'm going to muck around with it, but just for my own edification.
Is it stored with the NSObject, but hidden away in some Objective C implementation detail? If so, that seems like a bad design to me. One should be able to create their own root class and handle their own retain/release counting in a similar fashion (not that it's a good idea--one would have to have a very good reason not to use NSObject).
The storage location for the retain count depends on both the runtime in use and the class implementation.
For Apple's Objective-C runtime, you can figure out a lot by digging into the source code of the Objective-C runtime.
For example, if you're using ARC (and I think even if you're not), the reference counts for most objects are stored in hash tables. Have a look at the _objc_rootRetain function in runtime/objc-arr.mm. I don't know exactly why they did this. Perhaps it's a way of keeping retain counts together for better cache behavior (which is important under ARC because ARC adjusts retain counts more often than non-ARC code usually does).
However, some classes override retain and related methods and store the retain count elsewhere. For example, when debugging a memory leak I discovered that CALayer does this. Instead of using the runtime's normal retain count mechanism, a CALayer stores its retain count in a private C++ implementation object. This is rather frustrating because it means the Instruments Allocations instrument doesn't log retains and releases of CALayer objects.
We do not know exactly how the data is stored, but we can rule out a few options:
Private Implementation Variables
We can rule this out, simply because when we iterate through the iVars of the NSObject class, we see only one: isa, as shown through this program:
id object = [NSObject new];
Class meta = object->isa;
printf("class name: %s\n", class_getName(meta));
unsigned count;
Ivar *ivars = class_copyIvarList(meta, &count);
for (int i = 0; i < count; i++) {
printf("iVar: %s\n", ivar_getName(ivars[i]));
}
free(ivars);
And note that even private implementation properties exist in the class metdata.
Private Properties
We can also rule this out, as even private properties are exposed in the classes metadata, as shown by the following example, there are no properties for the NSObject class:
id object = [NSObject new];
Class meta = object->isa;
printf("class name: %s\n", class_getName(meta));
objc_property_t *properties = class_copyPropertyList(meta, &count);
for (int i = 0; i < count; i++) {
printf("property: %s\n", property_getName(properties[i]));
}
Associated Objects
This one is very hard to rule out, as there are no direct ways to get a list of all the associated objects. However, since the concept of associated objects is very new, and reference counting has been around forever, I say that this is not very likely.
CoreFoundation struct-mangling
This is my best guess. When you create a NSObject, it is a struct behind the scenes. What is to say that the actual NSObject data representation is something like this:
typedef struct CFObject {
int retainCount;
id isa;
} *CFObjectRef;
Then, when an object is created:
id object_createInstance(...)
{
CFObjectRef object = malloc(sizeof(struct CFObject));
...
return (id) (object + sizeof(object->retainCount));
}
int object_retainCount(id self)
{
CFObjectRef asObject = (CFObjectRef) (self - sizeof(asObject->retainCount));
return asObject->retainCount;
}
I cannot verify this however, as there are many other ways this could be done (a map of integers to objects, for example).
It doesn't sound like it, but just in case... if you're thinking of using retain count directly, don't.
As for implementation details, sessions at WWDC 2011 mentioned that under ARC, most of the reference counting implementation has moved into the ObjC runtime. Source for that is available, so you might be able to find out for yourself how it works. For manual reference counting, much of the ObjC behaviors are replicated in CoreFoundation and libdispatch, which are also open source -- if you're looking to implement a similar scheme yourself, those might prove educational.
In general, this is an implementation detail for the same reason many things are: encapsulation is good policy, especially for framework providers. You don't want users of a framework depending on implementation details because then you can't change your implementation without breaking their code.
Don't know if this would be relevant, but I've stumbled upon the blog post about higher order messages implementation in the Objective-C. There author implements the HOM object as a root class (i.e. not inherited from NSObject) and the implementation looks like this:
#interface HigherOrderMessage {
Class isa;
NSUInteger retainCount;
//not relevant to this question part
}
Then the retain count managing methods are implemented like this:
- (id)retain {
__sync_add_and_fetch(&retainCount, 1);
return self;
}
- (id)autorelease {
[NSAutoreleasePool addObject:self];
return self;
}
- (void)release {
if (__sync_sub_and_fetch(&retainCount, 1) == 0) {
[methodSignatureForSelector release];
[forward release];
object_dispose(self);
}
}
This code actually works, so although we do not know how exactly the retainCount is implemented in the Cocoa classes, it is certain that it could be implemented in some similar way.
For addition insight, check out http://www.mikeash.com/pyblog/friday-qa-2011-09-16-lets-build-reference-counting.html, where Mike Ash explores an alternative implementation like the one Apple uses.

self in Objective-C

is self not completely interchangeable with this in C++?
It seems to work with message passing ([ self sayHi ] would work within any method there).
I don't quite understand why I can't use self to access private members of an object (in the example below, I show I can't use self.width)
#import <Foundation/Foundation.h>
// Write an Objective-C class
#interface Rectangle : NSObject
{
int width ;
}
-(int)getWidth;
-(void)setWidth:(int)w;
-(void)sayHi;
-(void)sayHi:(NSString*)msg ;
#end
#implementation Rectangle
-(int)getWidth
{
// <b>return self.width ; // ILLEGAL, but why?</b>
// why can't I return self.width here?
// why does it think that's a "method"?
return width ;
}
-(void)setWidth:(int)w
{
// <b>self.width = w ; // ILLEGAL</b>
// again here, I CAN'T do self.width = w ;
width = w ;
}
-(void)sayHi
{
puts("hi");
}
-(void)sayHi:(NSString*)msg
{
printf( "Hi, and %s\n", [ msg UTF8String ] ) ;
}
#end
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Rectangle* r = [ Rectangle alloc ] ;
[ r sayHi ] ;
[ r setWidth:5 ] ;
printf( "width is %d\n", [ r getWidth ] ) ;
[pool drain];
return 0;
}
The other answers are almost correct, but not quite.
In Objective-C, no object [save for Blocks, but that is a very very special case] are ever on the stack. Thus, self.width doesn't make sense.
However, self->width does work. Since self is a reference to what is effectively a structure allocated on the heap, using the -> operator to get at the member variables makes sense.
But, in the context of Objective-C, it generally doesn't make sense, either. That is, Objective-C generally assumes a philosophy of preserving encapsulation. That is, you don't generally reach into an object and muck with the instance variables -- the internal state -- directly. Instead, you use the accessors to get/set the state. By doing so, the object (and subclasses) can customize getter/setter behavior, as needed. (This includes such mechanisms as Key-Value Observing and Key-Value Coding).
That self.width happens to equate to [self width] or [self setWidth: ...something...] is fallout from the above. That is, the . operator for accessing members of Objective-C class instances was not otherwise used and could be overloaded as a short hand for property access.
However, there is little difference between property access and invoke the getter/setter method. Thus, dot notation is synonymous with method invocation.
Within the context of your code, instance variables are transparently accessible within your classes implementation and without prefix.
Thus, you would use width = 5.0; instead of self.width = 5.0;, typically. Of course, the latter does equate to a method call with Objective-C 2.0 for reasons stated above.
You can't use self.width because it's not a property. self.width = w is shorthand for [self setWidth:w]; which was introduced in Objective-C 2.0. Try adding #property int width; above your method prototypes in the interface file, and at the top of your implementation file under the #implementation line, add #synthesize width;. That should allow you to use self.width, but it would no longer be a private variable.
You could also use #property (readonly) int width; to only generate a 'getter' method for width, but I doubt that's what you want. For more options you can pass to #property, check this documentation page.
Also, like Cliff said, getVar isn't convention in Objective-C. Instead, you just use the name of the variable you want to expose. The get prefix is usually used for when you're returning some form of raw data, as far as I know.
self.width is shorthand for [self width] and since you have not defined a width method it will be illegal. The getters in ObjC do not start with "get" by convention as they would in other languages like Java. Also I've heard from other experts (though I don't understand why) that it's not a good idea to use the property syntax from within the object that owns the proerty. From what I heard it causes some kind of a gotcha with Key Value Coding. In your example if you want to define a custom getter/setter then just reference the value directly without the self qualifier. It probably makes sense to use the getter/setter or dot notation everywhere else for good encapsulation.
self in Objective-C, like this in C++, is a pointer to the current object. So to access a field through self, you would do self->width (just as you would do this->width in C++)