Friday, September 28, 2012

How to get the attributes of an instance of NSTableView


How to get the attributes of an instance of NSTableView


The table view object (in MacOSx) is a collection of nested objects :

  • NSScrollView, 
  • NSTableView,
  • NSTableColumn
To get to a ojbect in this collection, 
  • hold down the Control and Shift keyswhile clicking on the table view. 
You will see a list of the objects under the cursor, and you can select the object you're interested in. 


How can you suppress compilers warning "can't find an implementation of accessor methods"


How can you suppress compilers warning "can't find an implementation of accessor methods"

#:fromDocumentation
You use the @dynamic statement to tell the compiler to suppress a warning if it can’t find an implementation of accessor methods specified by an @property declaration.
@implementation MyClass

@dynamic title;

@end

A summary of property-properties attributes - and some tips


A summary of property-properties attributes - and some tips


@Property attributes
Writability
readwrite
mutually exclusive
default
Indicates that the property should be treated as read/write
readonly

only a getter method is required
if you attempt to assign a value using the dot syntax, you get a compiler error.
A readonly property can redelcare it as readwrite in a  class extension, a protocol or in a subclass.
Setter
Semantics
assign (iOS 5)
unsafe_unretain (iOS4)




default

setter uses simple assignment (new value not retained, old value is not released).
use this for scalar types (NSInteger, CGRect in Ref.Counted env.
on dealloc method make sure that object propertis marked assign are not released and the not assign are released.
property=newValue;
retain
strong
if (property!=newValue){
 [property release];
property = [newValue retain];
retain should be invoked on the object upon assignment
the previous value is sent a release message
valid only for Objective-C object types (no for Core Foundation)
_attribute_
use attribute keyword to specify that a Core foundation property should be treated like an Objective C for memory management
copy

if (property!=newValue){
[property release];
property = [newValue copy];
}
a copy of the object should be used for assignment
previus value is sent a release message
valid only for objects that implement the NSCopying protocol
WARNING-the copy method returns an immutable version of a collection, so if you want a mutable version you need to implement the setter rather to synthesize it.
Atomicity
nonatomic
Specify that accessor methods are not atomic
(by default accessors are atomic=robust access to properties in a multithreaded environment)
If you specity retain or copy with not the noatomic, then in a reference-counted environment, a synthesized get accessor for an object property uses a lock and retains and autoreleases the returned value (similar to code below nonatomic)
[_internal lock]; //lock
id result = [[value retain] autorelease];
[_internal unlock];
return result;
Interface Outlet
IBOutlet

To specify that a property is an Interface Builder oulet
@property (nonatomic, retain) IBOutlet NSButton *myButton;


  • when you see __Blabla is for instance variables and Blabla is for property attribute.
  • For declared properties, you should use assign instead of weak; for variables you should use __unsafe_unretained instead of __weak.
  • You will always use unsafe_unretained for properties that hold non-objects.
  • For properties that hold objects, you will usually use strong
  • unsafe_unretained will have a "dangling pointer" if the object it points to is deallocated.
  • Their most common use is for delegates, where you'd define a property for that delegate with the weak orunsafe_unretained attribute (assign is effectively unsafe_unretained),
  • copy attribute is most common with object types that have mutable subclasses.
  • copy method returns an immutable copy.
  • Curiously the copy and mutableCopy methods are define in NSObject like this:
-(id) copy              {return [self  copyWithZone:NULL];}
-(id) mutableCopy {return [self mutableCopyWithZone:NULL];}

         So you need to be carefully in your custom objects (you need to override the copyWithZone etc).

  •   nonatomic option will make your setter method run a tiny bit faster. 

TIP_1: 
For iOS 5.0-Lion use __weak. For iOS4.0-Snow Leopard use __unsafe_unretained. Why?

 As its name implies, __unsafe_unretained will continue pointing to the memory where an object was, even after it was deallocated. This can lead to crashes due to accessing that deallocated object.
Why would you ever use __unsafe_unretained then? Unfortunately, __weak is only supported for iOS 5.0 and Lion as deployment targets. If you want to target back to iOS 4.0 and Snow Leopard, you have to use the __unsafe_unretained qualifier.


TIP_2:
Do you know that when compiling for iOS or a 64-bit Mac OS X (not for 32-bit Mac OSX) program, you don't need to declare the instance variables?
The @property/@ synthesize calls are sufficient to make the space for the data.
(from The big nerd ranch Guide)

Retain Cycle


Retain Cycle


Retain cycles are a very common source of memory leaks.

We have retain cycles when :
The object A has strong ownership on object B (direct or indirect) and the B has, also strong ownership at A.

That happens for example if the A has an MutableArray of objects B and some from objects B have strong ownership on object A.

the solution on theses cases is to use strong ownership (retain, alloc, etc) to child objects (B) and the child objects to have weak (__weak) ownership at the father.

Apple provides the Instrument profiling tool to help you with that.
When you profile a program, you monitor it while it runs to see what’s happening behind the scenes.



  • Xcode -> 
  • Product -> 
  • Profile … (Instruments launch) choose Leaks 
  • -> Choose Cycles to see if your project has some of them. 




#:from Objective - C programming: The big Nerd Ranch Guide

Callbacks - short notes


For Objective-C programmers, there are three-forms that a callback can take.

  • -       TARGET-ACTION: before the wait begins you say “When x happens, send this particular message to that particular object,” The object receiving the message is the target. The selector for the message is the action.
  • -       Helper objects: Before the wait begins, you say “Here is a helper object that conforms to your protocol. Send it messages when things happen”. Helper objects are often known as delegates or data sources.
  • -       Notifications: There is an object called the notification center. Before the wait begins, you say to the notification center “This object is waiting for these sorts of notifications. When one of those notifications arrives, send the object this message”. When x happens, an object posts a notification to the notification center, and the center forwards it on to your object.

Types of Callbacks
Target-Action
sending ONE    callback   to ONE object
timers,simple user interface controls(buttons, sliders etc)
Helper objects
(delegate or data source)
sending MANY callbacks to ONE object
NSURLConnection.
The most common type of helper object is the delegate
Notifications
sending MANY callbacks to Multiple object
Notification center


Notes:
-       Notification centers do not own their observers (they typically remove itself from notification in its dealloc method)
-       Objects do not own their delegates or data sources (if you create an object that is delegate or data source, your object need to “clear” himself in its dealloc method). Exception: NSURLConnection owns its delegate
-       Objects do not own their targets. (if you create an object that is a target, your object should zero the target pointer in its dealloc method).Exception: NSTimer owns it’s target.



#:From The Big Nerd Ranch Guide Objective C programming

isa - super - self


isa - super - self

short notes:

isa
  • NSObject has many methods, but only one  instance variable: the isa pointer. 
  • Every object's isa pointer points back to the class that created it. 
  • We call it the isa pointer because an object "is a " instance of that class.  At runtime when a message is sent to an object, that object goes to the class named in its isa pointer and says, "I was sent this message. Run the code for the matching method". This is different than most compiled languages, where the method to be executed is determined at compile time. 
  • The isa pointer, as the name suggests, points to the object's class which maintains a dispatch table. This dispatch table essentially contains pointers to the methods the class implements, among other data. 
  • The value of the isa pointer does not necessarily reflect the actual class of the instance. When an observer is registered for an attribute of an object the isa pointer of the observed object is modified, pointing to an intermediate class rather than at the true class. 
  • You should never rely on the isa pointer to determine class membership. Instead, you should use the class method to determine the class of an object instance. 

A little confused from the above i will get back on this ..!?!?!?

super:

  • To be precise, the super directive says "Run this method, but start the search for its implementation at my superclass".
  • Each version of init follows this procedure, so classed initialize theri instance variables in the order of inheritance

- (id) init
{
  self = [super init];
  if (self) {
  ...
  }
}

  • super is simply a flag to the compiler telling it where to begin searching for the method to perform; it's used only as the receiver of a message. But self is a variable name that can  be used in any number of ways, even assigned a new value (see Redefining self)
  • super is a flag that tells the compiler to search for the method implementation, begins in the superclass of the class that defines the method where super appears. 
  • wherever super receives a message, the compiler substitutes another messaging routine for the objc_msgSend function. 



self:

  • is one of the hidden parameters that the messaging routine passes to every method; it's a local variable that can be used freely within a method implementation, just as the names of instance variables
  • self searches for the method implementation in the usual manner, starting in the dispatch table of the receiving object's class. 



from Big Ned Ranch Guide Object C & ios Programming + Documentation

How we import (constant) global variables and #define VS global variables


How we import (constant) global variables and #define VS global variables


One of them informs the preprocessor to do a textual substitution. The other actually declares a (constant) C variable.


#define VS global variables - enum


define informs the preprocessor to do a textual substitution (a macro)
global variables - enum - declares a (constant) variable.


so its like macro VS const variable. 


The global variables - enum

  • they obey the language's scoping rules 
    you can see them in the debugger 
    you can take their address if you need to 
    you can pass them by const-reference if you need to 
    they don't create new "keywords" in your program.



you should use global variables and enum for constants, not #define.


How we import global variables?



  • 1) Add 2 new files to your project: "GlobalValues.h" and "GlobalValues.m".
  • 2) Open "GlobalValues.h", and declare all your needed variables.
//name of the 'service' used for storing items in the user's keychain:
extern NSString const *MYKeychainServiceName;

//name of the PasteBoard data type that application uses for document data:
extern NSString const *MYPboardDataType;
  • 3) Open "GlobalValues.m", and start the new file by importing "GlobalValues.h".
  • 4) Then, assign values to the variables you declared in the header file:
#import "GlobalValues.h"

//name of the 'service' the application uses for storing items in the user's keychain:
NSString const *MYKeychainServiceName = @"MyApplication Password";
//name of the PasteBoard data type that application uses for document data:
NSString const *MYPboardDataType = @"MyApplication DocData";
In the implementation files of the classes that need to use these variables, you would put - at the very beginning:
#import "GlobalValues.h"


#source:
Big Nerd Ranch Guide - Objective C programming
http://www.cocoadev.com/index.pl?GlobalVariablesInCocoa 

NSArray remove ObjectIdenticalTo VS removeObject:


NSArray remove ObjectIdenticalTo VS removeObject:

copy (and not paste!) from book BigNerd Ranch iOS programming (2012) page 214


  • removeObjectgoes to each object in the array and sends it the message isEqual:. A class can implement this method to return YES or NO based on its own determination
  • removeObjectIdenticalTo: removes an object if and only if it is exact same object as the one passed in this message. 

How to pass arguments in object C - xcode programes


How to pass arguments in object C - xcode programes


in Xcode:
  • Choose Produce from menu
  • Choose Edit Scheme
  • Select Run ApplicationName on the left
  • Select Arguments tab
  • Add Arguments with + on Arguments Passed on Launch

JSON format


JSON format


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming LanguageStandard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.
In JSON, they take on these forms:
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.

Bitwise operator OR and AND - in objective C - Exclusive OR - Complements - Shifting and Enum


Bitwise operator OR and AND - in objective C - Exclusive OR - Complements - Shifting and Enum


  • | is the bitwise-OR operator in C. 


You will see the bitwise-OR operator a lot in Cocoa and iOS programming.
You can use bitwise-OR together the constants that represent the particular aspects you want.


NSError *e;
NSDataDetector *d = [NSDataDetector dataDetectorWithTypes:
                                             NSTextCheckingTypePhoneNumber | NSTextCheckingTypeDate
                                             error:&e];


  • In objective-C we use bitwise-AND (&) to see if a certain bit, or flag is on

if ([currentDetector checkingTypes] & NSTextCheckingTypePhoneNumber){
    NSLog (@"This one is looking for phone numbers");
}



  • ^ exclusive OR (XOR) - two bytes together to create a third (beware is not exponentiation operator=pow())
  • complement is the byt that is the exact opposite of another (reverse all the 0 to 1 and all the 1 becomes 0).
  • A<<2 .="." b="b" nbsp="nbsp"><< Left-shift
. Every time you left -shift a number one place, you double tis value.
  • A>>1. >>Right-shift. Every time you right-shift a number one place, you half its value (if it is odd round down).

  • An elegant way to declare the bit-masks with enum
    enum {
     UIDataDetectorTypePhoneNumber = 1 << 0,
     UIDataDetectorTypeLink                = 1 << 1,
     UIDataDetectorTyprAddress           = 1 << 2,
     UIDataDetectorTypeNone               =0,
     UIDataDetectorTypeAll                   = NSUIntegerMax
    };




    examples from The big Nerd Ranch Guide - Objective C 

    Categories


    Categories

    An easy way to add methods to any existing class.

    #import "ClassName.h"
    @interface ClassName ( CategoryName )
    // method declarations
    @end

    From Documentation:
    How You Can Use Categories
    There are several ways in which you can use categories:
    • To extend classes defined by other implementorsFor example, you can add methods to the classes defined in the Cocoa frameworks. The added methods are inherited by subclasses and are indistinguishable at runtime from the original methods of the class. 
    • As an alternative to a subclassRather than define a subclass to extend an existing class, through a category you can add methods to the class directly. For example, you could add categories to NSArray and other Cocoa classes. As in the case of a subclass, you don’t need source code for the class you’re extending.
    • To distribute the implementation of a new class into multiple source files For example, you could group the methods of a large class into several categories and put each category in its own file. When used like this, categories can benefit the development process in a number of ways—they:
      • Provide a simple way of grouping related methods. Similar methods defined in different classes can be kept together in the same source file.
      • Simplify the management of a large class when several developers contribute to the class definition.
      • Let you achieve some of the benefits of incremental compilation for a very large class.
      • Can help improve locality of reference for commonly used methods.
      • Enable you to configure a class differently for separate applications, without having to maintain different versions of the same source code.
    • To declare informal protocols See “Informal Protocols ,” as discussed under “Declaring Interfaces for Others to Implement.”
    Although the Objective-C language currently allows you to use a category to override methods the class inherits, or even methods declared in the class interface, you are strongly discouraged from doing so. A category is not a substitute for a subclass. There are several significant shortcomings to using a category to override methods:
    • When a category overrides an inherited method, the method in the category can, as usual, invoke the inherited implementation via a message to super. However, if a category overrides a method that exists in the category's class, there is no way to invoke the original implementation.
    • A category cannot reliably override methods declared in another category of the same class.This issue is of particular significance because many of the Cocoa classes are implemented using categories. A framework-defined method you try to override may itself have been implemented in a category, and so which implementation takes precedence is not defined.
    • The very presence of some category methods may cause behavior changes across all frameworks. For example, if you override the windowWillClose: delegate method in a category on NSObject, all window delegates in your program then respond using the category method; the behavior of all your instances ofNSWindow may change. Categories you add on a framework class may cause mysterious changes in behavior and lead to crashes.

    NSLog - Tokens - %@ - %p memory token, %zu size_T token (tip to find the type (32 or 64 bit) of environment)


    NSLog - Tokens - %@ - %p memory token, %zu size_T token (tip to find the type (32 or 64 bit) of environment)

    in NSLog the first argument is required and must be an NSString instance.
    This instance is called the format string and it contains text and a number of tokens.
    The tokens (also called format specifications) are prefixed with a percent (%) symbol.

    • With the %@ is encountered in the format string, instead of the token being replaced by the corresponding argument, that argument is sent the message description. The description methodreturns an NSString that replaces the token. Every object implements the method description.
    • With the %p token you can see the memory address of a variable or functions name!.

        %@ Object, calls the Object's description method
        %d, %i signed int
        %u unsigned int
        %f float/double
        %p for pointers to show the memory address
        %zu value of type size_t (for sizeof(variable function)
        %s C strings
        \u can used for arbitrary unicode chars example:NSLog(@"\u03c0");//π



    ------------------------------
    Variables:
    int i =17;
    printf("i stores the value at the address %p\n", &i);

    i stores its value at 0xbfffb749

    Function name
    printf("the main function starts at %p", main);


    • With the %zu you can return a value of type size_t (for sizeof(variable) function)

    printF("A pointer is %zu bytes", sizeof(int *));
    4 bytes long pointer = 32 bit mode
    8 bytes long pointer = 64 bit mode



    • With the \u you can use arbitrary unicode chars 
    NSLog (@"\u03c0"); // π 

    Last edit: 19/5/2012
    Last edit: 21/4/2012
    Last edit: 22/3/2012

    What Is Key-Value Coding?


    What Is Key-Value Coding?
    Key-value coding is a mechanism for accessing an object’s properties indirectly, using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables. In essence, key-value coding defines the patterns and method signatures that your application’s accessor methods implement.
    Accessor methods, as the name suggests, provide access to your application’s data model’s property values. There are two basic forms of accessor—get accessors and set accessors. Get accessors, also referred to as getters, return the values of a property. Set accessors, also referred to as setters, set the value of a property. There are getter and setter variants for dealing with both object attributes and to-many relationships.
    Implementing key-value coding compliant accessors in your application is an important design principle. Accessors help to enforce proper data encapsulation, isolatememory management to centralized locations, and facilitate integration with other technologies such as key-value observing, Core Data, Cocoa bindings, and scriptability. Key-value coding methods can, in many cases, also be utilized to simplify your application’s code. See Model Object Implementation Guide for more guidance on why your application should implement key-value coding compliant accessors and make use of them.
    The essential methods for key-value coding are declared in the NSKeyValueCoding Objective-C informal protocol and default implementations are provided by NSObject.
    Key-value coding supports properties with object values, as well as the scalar types and structs. Non-object parameters and return types are detected and automatically wrapped, and unwrapped, as described in “Scalar and Structure Support.”

    examples:
    Object types:
    [a setProductName:@"Washing Machine"]
    [a setValue:@"Washing Machine" forKey:@"productName"];

    [a valueForKey:@"productName"]

    Non-object types
    [a setVoltage:240];
    [a setValue:[NSNumber numberWithInt:240] forKey:@"voltage"];

    some notes from The Big Nerd Ranch Guide:
    Note that even though you have no accessor methods for one object, the variable can still be set and read from others methods (via key-value coding). This is an obvious violation of the idea of object encapsulation - methods of an object are public, but the instance variables are delicate and should be kept private. If key-value coding weren't astonishingly useful, no one would tolerate it.

    Charbonneau is correct. I get an XML feed in which corresponds to an object on the iPhone/Mac client. Typically it'll be something like Bob43 I had a method before that would key/value code NSDictionary instances. – Coocoo4Cocoa Dec 18 '08 at 20:53

    Blocks


    Blocks

    ^(double div, double divisor) {
      double quotient = div / divisor;
      return quotient;
    };

    ^: identifies a block

    Block can take arguments

    If you want to access a block by a name, we have to assign it to a block variable.

    void (^devow) (id, NSUInteger, BOOL *)
    Block variable declaration


    notice that the block assignment ends with a semi-colon just like any variable assignment would.

    You can use typedef to declare a block at the start of top of the file like
    typedef void (^ArrayEnumerationBlock) (id, NSUInteger, BOOL *);

    Rather to write: void (^devowelizer) (id, NSUINteger, BOOL *);
    you can   write: ArrayEnumerationBlock devowelizer;

    If a block returns a value you can call that block variable like a function

    double (^divinationBlock) (double, double) = ^(double k, double j) {
                return k/j;
    }

    Blocks are created and stored on the stack and will be destroyed (with the stack) when the function or method that created the block returns. To copy a block from the stack to the heap, you send it the copy message:
    ArrayEnumerationBlock iVarSomething = [something copy]; (now the new block variable is a pointer to the block).Methods that takes blocks as arguments, are expected to copy blocks passed to them.
    A heap-based block behaving like an object comes with some memory management issues:

    #Source: The Big Nerd Ranch Guide (Objective C) - kindle version


    • external variables are captured by the block when the copy is made.
    • to avoid retain cycles declare a __weak pointer outside the block
    • variables captured by a block are constant within the block and you cannot change their values (you can still send the object messages that can change its contentsyou cannot modify the pointer itself).
    • if you want to change them you need to use __block otherwise you get compilation error.
    __block int counter =0 ;
    void (^counterBlock) () = ^ {counter++;};
    ...
    counterBlock (); //Increments counter to 1
    counterBlock ();//Increments counter to 2

    Wy shouldn't I use accessor methodes in an init method?


    Wy shouldn't I use accessor methodes in an init method?

    First: Apples Documentation says so...

    Don’t Use Accessor Methods in Initializer Methods and dealloc
    The only places you shouldn’t use accessor methods to set an instance variable are in initializer methods and dealloc. To initialize a counter object with a number object representing zero, you might implement an init method as follows:
    - init {

        self = [super init];

        if (self) {

            _count = [[NSNumber alloc] initWithInteger:0];

        }

        return self;

    }

    To allow a counter to be initialized with a count other than zero, you might implement an initWithCount: method as follows:
    - initWithCount:(NSNumber *)startingCount {

        self = [super init];

        if (self) {

            _count = [startingCount copy];

        }

        return self;

    }

    Since the Counter class has an object instance variable, you must also implement a dealloc method. It should relinquish ownership of any instance variables by sending them a release message, and ultimately it should invoke super’s implementation:
    - (void)dealloc {

        [_count release];

        [super dealloc];

    }



    What stackoverflow says? 

    • It's basically a guideline to minimize the potential for bugs.
    • It is all about using idiomatically consistent code. If you pattern all of your code appropriately there are sets of rules that guarantee that using an accessor in init/dealloc is safe.





    What Big Nerd Ranch guide says?
    "..In most cases, there is a little reason to do one over the other, but it makes for a great argument. The argument goes like this: The assign guy says, "You can't use an accessor method in an init method! The accessor asumes that the object is ready for work, and it isn't ready for work until after the init method is complete." Then the accessor method guy says, "Oh, come on. In the real world that is almost never an issue. My accessor method might be taking care of other stuff for me. I use my accessor anytime I set that variable." In reality, either approach will work in the cast majority of cases.