Best objective-c questions in August 2010

Tutorial on How to drag and drop item from UITableView to UITableView

15 votes

I've been banging my head on this one for a while and I figured it out. I want to give back to the community since I've gotten a lot of help from this website :).

I'm trying to copy an item from one UITableView to another UITableView and information I've seen on the web regarding how to do this has been sketchy at best. I figured it out on my own and so I'll describe my little architecture.

  • Master UIView
    • UIView with UITableView
      • Custom UITableViewCell
        • Custom UIView that gets copied (Person object in my case)
    • UIView with UITableView
      • Custom UITableViewCell
        • Custom UIView that gets copied (Person object in my case)

The person object that I have in the UITableView is the object that I want to drag and drop out of one table and into another. I had the most difficult figuring out how to pop the item out of the table and drag it over in a single smooth motion. For the longest time, it would take me two touches in order to perform the operation.

Starting with the Person object, this is a simple object that contains an image. I had to implement my own touchesMoved method to change the center position of the Person when a drag is taking place.

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    if( m_moveable == YES ){
        UITouch *touch = [touches anyObject];
        CGPoint location = [touch locationInView:self.superview];

        if( 0 < location.x-50 && location.x+50 < 768 ){ 
            if( 0 < location.y-50 && location.y+150 < 1004 ){
                self.center = location;
            }
        }
    }
}

I set the Person object's userInteractionEnabled flag to NO on initialization so that any clicks in the table would not get caught by the Person object. The Person object in that case would move within the table which defeats the purpose.

The next object is my custom UITableViewCell. This object is responsible to catch the user's first touch. What it's supposed to do is catch this touch and "pop" the Person out. The Person is one of the subviews belonging to the custom UITableViewCell.

 - (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UIView *parent = self.superview.superview.superview;    

    Person *s = nil;
    for( UIView *child in self.subviews ){
        if( [child isKindOfClass:[Person class]] ){
            s = child;
            s removeFromSuperview];
            break;
        }        
    }

    if( s != nil ){
        self.userInteractionEnabled = NO;
        s.userInteractionEnabled = YES;
        UITableView *subParent = self.superview;   //EDIT #1
        subParent.scrollEnabled = NO;              //EDIT #1

        [parent addSubview:s];
        //[self touchesEnded:touches withEvent:event]; //EDIT #1
    }
}

It's important to note the userInteractionEnabled flag getting flipped in the above method. Before the touch, the Person object is "off limits" to a person's touch. After the custom cell catches a move, the Person is released by adding it to the parent's view and then activated (userInteractionEnabled=YES). The Person object is then "born" and can handle move touches on it's own.

This has one minor glitch in that the Person object blinks in the upper left corner but then drops down immediately to the user's finger.

The final part of this design is that the master UIView needs to handle a "touch transition." When the user is touching the table and the Person object gets popped out, the app needs to realize that focus needs to be removed from the table and directed towards the Person object. The way that this was done is that the hitTest method in the master UIView was overloaded with the following.

- (UIView*) hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *rv = nil;
    for(UIView *child in self.subviews){
        if( [child isKindOfClass:[Person class]] ){
            rv = child;
            child.center = point;
            break;
        }
    }
    if( rv == nil ){
        rv = [super hitTest:point withEvent:event];
    }   
    return rv;
}

The way that this code works, is that when the Person is popped out of the table, it doesn't have a touch focused at it. The touch is "owned" by the UITableView from which the Person was popped out of. The hitTest method is the key to refocusing that touch. Regularly, the system checks to see which UIView is the focus of a touch. The hitTest method is called by the system to identify that UIView. When the Person is attached to the master view, this hitTest function iterates through all subviews and detects the presence of the Person and returns it as the "dominant" touched object. Any movement of your finger will immediately be reported to the Person and not to the UITableView.

This is guts of the implementation. To have a UITableView "catch" the moving object is simple now and I'll leave it for you to try! If you have any questions, please post them!

EDIT #1 Dropping the Person object is proving harder than I thought :). I had to add a line to prevent the UITableView from scrolling when the parent is being moved around because the UITableView is sucking in all the movement events.
The touchesEnded function fires in the custom UITableViewCell class.
mj

Hi I've managed to create drag&drop of a row in a UITableView onto another row of the same table. I created a uiImageView representing the moving item (which was not removed from the table) and attached it to the frontmost UIView to made it draggable on the whole screen. Here are some post about the pains I faced:

  1. http://stackoverflow.com/questions/3378060/uitableview-drag-a-row-onto-another-one
  2. http://stackoverflow.com/questions/3457900/uitableview-scrolling-programmatically-the-content-view
  3. http://stackoverflow.com/questions/3417808/uitableview-custom-gestures-make-it-scrolling-no-more

Hope this can help ^^

Objective C: Blocks vs. Selectors vs. Protocols

11 votes

I frequently find myself writing "utility" classes that can be re-used throughout my projects.

For example, suppose I have an "Address Book" view. I might want to use my address book to select who gets sent an email, or maybe who gets added to a meeting request.

I'd develop this view controller so it can be used by both the email controller, and the meetings controller, with some sort of callback mechanism to let the caller know the user either finished selecting someone from the address book, or they canceled.

It seems there are basically four (reasonable) approaches one might take in this scenario;

  • Create an "AddressBookDelegate" protocol and a corresponding delegate property on the AddressBookController. Then use the messages defined in the protocol to communicate the result (similar to UIActionSheetDelegate).

  • Create an "informal" "AddressBookDelegate" protocol and a corresponding delegate property on the AddressBookController, but the type of the delegate property will be "id", and will check at runtime with "respondsToSelector:" to see if the delegate implements the methods we require (seems like most of the framework stuff has started going this way).

  • Pass the AddressBookController an id that represents a delegate, as well as two SELs which specify the methods to call when the user selects a user or cancels the request. The benefit I see with this is; suppose one controller supports BOTH sending emails AND setting up meetings (I know in this example that seems like bad design... but one can imagine a more generic situation where this would seem perfectly reasonable for a utility class) - In this case you could pass the AddressBookController different SELs depending on whether you're adding users to an email, or adding users to a meeting... a huge improvement over an iVar to indicate the controller's "state".

  • Pass the AddressBookController two blocks; one to run when the user selects someone from the address book, and one to run if the user cancels the request.

The blocks have been so tremendously useful to me, and SO much more elegant, I'm finding myself almost confused over when to NOT use them.

I'm hoping more experienced members of the StackOverflow community than I can help out with their thoughts on this topic.

The 'traditional' way to do this is with a protocol. Informal ones were used before @protocol was added to the language, but that was before my time and for at least the last few years informal protocols have been discouraged, especially given the @optional specifier. As for a 'delegate' which passes two SELs, this just seems more ugly than declaring a formal protocol, and generally doesn't seem right to me. Blocks are very new (esp. on iOS), as these things go, and while we have yet to see the tremendous volume of documentation/blogs on the best tried and true style, I like the idea, and this seems to be one of the things blocks are best for: neat new control flow structures.

Basically what I'm trying to say is that each of these methods vary in age, with none being better than the last except for style, which obviously counts for an awful lot, and is ultimately why each of these things was created. Basically, go with the newest thing you feel comfortable with, which should be either blocks or a formal protocol, and that your confusion is most likely coming from reading conflicting sources because they were written at different times, but with time in perspective, it is clear to see which super seeds the others.

[Controller askForSelection:^(id selection){
  //blah blah blah
} canceled:^{
  //blah blah blah
}];

is probably a hell of a lot more concise than defining two extra methods, and a protocol for them (formally or otherwise) or passing the SELs and storing them in ivars, etc.

Best book / resources for learning iOS programming?

10 votes

Which resources did you find useful for learning iOS programming?

Books? Website? Videos?

Apples's documentation is decent at best; I'd recommend a series of books to get you going. I've read loads of them and my recommendation (read in this order) would be:

Programming in Objective-C 2.0 by Stephen Kochan for the Objective-C foundation. Do you know Objective-C? Do you know any C? If the answer is no to either of these, then definitely start here. From what I remember it also comes with videos.

One of the Apress books for your foundation iOS SDK learning: Beginning iPhone Development: Exploring the iPhone SDK by Dave Mark and Jeff LaMarche ramps up very well for a beginner and covers most of what you'd need to know to make a complete application from design to delivery.

And finally The iPhone Developer's Cookbook by Erica Sadun for additional badassery. I learned more from Erica's book than any other source. If you only buy one book, BUY THIS ONE. It's awesome, provides insane code source, loads of workarounds and useful helper classes and hacks.

My favorite introduction websites are:

  • Theocacao (make sure you read the topics on memory management and how @property works behind the scenes)
  • CIMG. Loads of great topics and tips.
  • Find the authors of these books on Twitter and follow them. Seriously, they post sample code, tips, and will help you directly. I've found it invaluable.
  • Open Radar. Developing for iOS 4.0? You'll want to get to know this site as 4.0 is buggy as hell.

Definitely check out Stanford's Video class on Itunes U. I watched those after my introduction to Objective-C/iPhone and wished I had that when I started.

Apple's developer forums seem to be a nice place to rant about how much the SDK is broken, but beyond that I have not found much use for it. Apple's documentation has very little sample code and their samples on the site are dated (and often straight broken).

At the end of the day, though, your best learning experience will be deciding to make an application and following through. You'll find how ridiculously hard some menial tasks are and how pleasingly easy other tasks are with the SDK. It's a up and down roller coaster no matter how much you know going in.

Prefixing property names with an underscore in Objective C

8 votes

I've always avoided underscores in my variable names, perhaps because its just not what was done back in my learning Java in college days. So when I define a property in Objective C this is what I naturally do.

//in the header
@interface Whatever
{
    NSString *myStringPorperty
}

@property (nonatomic, retain) NSString *myStringProperty;

//in the implementation
@synthesize myStringProperty;

But in almost every example it is done like

//in the header
@interface Whatever
{
    NSString *_myStringPorperty
}

@property (nonatomic, retain) NSString *myStringProperty;

//in the implementation
@synthesize myStringProperty = _myStringProperty;

Should I get over my aversion to the underscore because that is the one way it should be done, is there a good reason for this style being the preferred one?

Current suggested Objective-C 2.0 practice is to use the same name for the ivar as the property. You can optionally assign a different ivar in the @property declaration, but the fact that by default, synthesized accessors for a property will access the ivar with the same name as the property indicates that's the pattern they expect you to follow.

No matter what, since objects still have to send messages to themselves to access properties, it's hard to confuse when you're accessing a property or when you're accessing its backing ivar directly, though using the 2.0 dot access to properties does make it more possible. Using the standard message passing syntax makes intent more explicit, IMO.

@interface Foo : NSObject {
     NSNumber *bar;
} 
@property(readwrite, retain) NSNumber * bar
@end

@implementation Foo 
@synthesize bar

-(void) baz {
   NSNumber *numberOne = [NSNumber numberWithInt: 1];   
   //Both set the value of bar through either the your custom or the synthesized setter method
   [self setBar:numberOne];  
   self.bar = numberOne; 

   //Both get the value of bar through your synthesized or your custom accessor method
   NSNumber *fooBar = [self bar];
   fooBar = self.bar;

   //Both manipulate the bar ivar directly
   bar = numberOne;
   fooBar = bar;
}
@end 

Time each CPU core spends in C0 power state

7 votes

The title says it all. Any help figuring out how to do this would be great: How much time each CPU core spent in the C0 power state over the past second.

This is for a mac app so Objective-C, cocoa and c are needed.

Thank you!

OS X doesn't have any APIs that expose the c-state of the CPU. However, it seems like you can do this using the MWAIT/MONITOR instructions on intel CPUs. Intel mentions that you can track C-state residency using this technique in section 14.4 of the reference manual:

Software should use CPUID to discover if a target processor supports the enumeration of MWAIT extensions. If CPUID.05H.ECX[Bit 0] = 1, the target processor supports MWAIT extensions and their enumeration (see Chapter 3, “Instruction Set Reference, A-M,” of Intel® 64 and IA-32 Architectures Software Developer’s Manual, Volume 2A).

If CPUID.05H.ECX[Bit 1] = 1, the target processor supports using interrupts as break-events for MWAIT, even when interrupts are disabled. Use this feature to measure C-state residency as follows:

  • Software can write to bit 0 in the MWAIT Extensions register (ECX) when issuing an MWAIT to enter into a processor-specific C-state or sub C-state.
  • When a processor comes out of an inactive C-state or sub C-state, software can read a timestamp before an interrupt service routine (ISR) is potentially executed.
  • You can find more info about the MWAIT instruction in the same manual. Good luck!

    Intel's Reference Manual

    Understanding the bitwise AND Operator

    6 votes

    I have been reading about bit operators in Objective-C in Kochan's book, "Programming in Objective-C".

    I am VERY confused about this part, although I have really understood most everything else presented to me thus far.

    Here is a quote from the book:

    The Bitwise AND Operator

    Bitwise ANDing is frequently used for masking operations. That is, this operator can be used easily to set specific bits of a data item to 0. For example, the statement

    w3 = w1 & 3;
    

    assigns to w3 the value of w1 bitwise ANDed with the constant 3. This has the same ffect of setting all the bits in w, other than the rightmost two bits to 0 and preserving the rightmost two bits from w1.

    As with all binary arithmetic operators in C, the binary bit operators can also be used as assignment operators by adding an equal sign. The statement

    word &= 15;
    

    therefore performs the same function as the following:

    word = word & 15;
    

    Additionally, it has the effect of setting all but the rightmost four bits of word to 0. When using constants in performing bitwise operations, it is usually more convenient to express the constants in either octal or hexadecimal notation.

    OK, so that is what I'm trying to understand. Now, I'm extremely confused with pretty much this entire concept and I am just looking for a little clarification if anyone is willing to help me out on that.

    When the book references "setting all the bits" now, all of the bits.. What exactly is a bit. Isn't that just a 0 or 1 in 2nd base, in other words, binary?

    If so, why, in the first example, are all of the bits except the "rightmost 2" to 0? Is it 2 because it's 3 - 1, taking 3 from our constant?

    Thanks!

    Numbers can be expressed in binary like this:

    3    = 000011
    5    = 000101
    10   = 001010
    

    ...etc. I'm going to assume you're familiar with binary.

    Bitwise AND means to take two numbers, line them up on top of each other, and create a new number that has a 1 where both numbers have a 1 (everything else is 0).

    For example:

        3          =>  00011
      & 5          =>  00101
    ------           -------
        1              00001
    

    Bitwise OR means to take two numbers, line them up on top of each other, and create a new number that has a 1 where either number has a 1 (everything else is 0).

    For example:

        3          =>  00011
      | 5          =>  00101
    ------           -------
        7              00111
    

    Bitwise XOR (exclusive OR) means to take two numbers, line them up on top of each other, and create a new number that has a 1 where either number has a 1 AND the other number has a 0 (everything else is 0).

    For example:

        3          =>  00011
      ^ 5          =>  00101
    ------           -------
        0              00110  
    

    Bitwise NOR (Not OR) means to take the Bitwise OR of two numbers, and then reverse everything (where there was a 0, there's now a 1, where there was a 1, there's now a 0).

    Bitwise NAND (Not AND) means to take the Bitwise AND of two numbers, and then reverse everything (where there was a 0, there's now a 1, where there was a 1, there's now a 0).

    Continuing: why does word &= 15 set all but the 4 rightmost bits to 0? You should be able to figure it out now...

         n          =>  abcdefghjikl
      & 15          =>  000000001111
    ------            --------------
         ?              00000000jikl
    

    (0 AND a = 0, 0 AND b = 0, ... j AND 1 = j, i AND 1 = i, ...)

    How is this useful? In many languages, we use things called "bitmasks". A bitmask is essentially a number that represents a whole bunch of smaller numbers combined together. We can combine numbers together using OR, and pull them apart using AND. For example:

    int MagicMap = 1;
    int MagicWand = 2;
    int MagicHat = 4;
    

    If I only have the map and the hat, I can express that as myInventoryBitmask = (MagicMap | MagicHat) and the result is my bitmask. If I don't have anything, then my bitmask is 0. If I want to see if I have my wand, then I can do:

    int hasWand = (myInventoryBitmask & MagicWand);
    if (hasWand > 0) {
      printf("I have a wand\n");
    } else {
      printf("I don't have a wand\n");
    }
    

    Get it?

    EDIT: more stuff

    You'll also come across the "bitshift" operator: << and >>. This just means "shift everything left n bits" or "shift everything right n bits".

    In other words:

    1 << 3 = 0001 << 3 = 0001000 = 8

    And:

    8 >> 2 = 01000 >> 2 = 010 = 2

    Objective-C Runtime: best way to check if class conforms to protocol?

    6 votes

    I have a Class (but no instance) and need to know if it conforms to a certain protocol. However, Class can be subclassed several times and class_conformsToProtocol() ignores protocols declared on superclasses.

    I could just use class_getSuperclass() and recursively check all the classes in the hierarchy upwards until the superclass is nil. However I wonder if that might be inefficient for deeply nested class hierarchies, and maybe there's a nicer way to do that?

    In other words, how is the NSObject method conformsToProtocol best implemented using Objective-C runtime methods so that it finds protocols on superclasses?

     [myObject conformsToProtocol:@protocol(MyProtocol)];
    

    If I'm on the right track with recursively going up the class hierarchy just let me know.

    According to the docs,

    [MyClass conformsToProtocol:@protocol(MyProtocol)];
    

    should work.

    Does it matter when super is called in dealloc?

    6 votes
    - (void)dealloc {
        [super dealloc];
        [receivedData release]; receivedData = nil;
    }
    

    or

    - (void)dealloc {
        [receivedData release]; receivedData = nil;
        [super dealloc];
    }
    

    Yes, it absolutely maters when [super dealloc] is called. Once [super dealloc] is called, you can no longer rely on the NSObject (or whatever your root class is) machinery to function properly. Afterall, your super-class' -dealloc method should call its superclass' etc. until the root class' -dealloc method is called. At that point, everything that these classes allocate to do their job is potentially gone and you're in undefined territory if you try to use any of it.

    Your -dealloc method should always look like

    - (void)dealloc
    {
       // release my own stuff first
    
       [super dealloc];
    }
    

    Hide text selection handles after action in UIWebView

    6 votes

    I have several custom UIMenuItems that do things with a selection in a UIWebView. After the action has been run on that selection I want to hide the selection handles just as copy: does.

    I have tried using window.getSelection().removeAllRanges(); and that works in that window.getSelection() no longer returns anything but the text selection handles stay visible.

    Is there a way to remove the selection and the handles with it?

    Edit: I don't need it to be a JS solution but I can't loose the state by reloading the webview.

    Just disable and re-enable the User Interaction:

    myWebView.userInteractionEnabled = NO;
    myWebView.userInteractionEnabled = YES;
    

    Does pushViewController retain the controller?

    6 votes

    I am struggling to find out if pushViewController retains the controller, currently I have the following code (which works) ...

    ColorController *colorController = [[ColorController alloc] initWithNibName:nibColor bundle:nil];
    [[self navigationController] pushViewController:colorController animated:YES];
    [colorController release];
    

    but am considering removing the release and adding an autorelease ...

    ColorController *colorController = [[[ColorController alloc] initWithNibName:nibColor bundle:nil] autorelease];
    [[self navigationController] pushViewController:colorController animated:YES];
    

    Much appreciated

    Gary

    This does nothing...

    ColorController *colorController = [[ColorController alloc] initWithNibName:nibColor bundle:nil];
    [[[self navigationController] pushViewController:colorController animated:YES] autorelease];
    

    You are autoreleasing the return value of pushViewController:animated:, which is void.

    Your first snippet is valid, and correct. pushViewController: does indeed retain the controller that is pushed.

    Edit: In your updated code, there is little difference between the two samples. Both maintain proper retain counts. However, it is a "best practice" to avoid using autoRelease unless necessary (especially in a memory sensitive area, like the iPhone). This helps your application to maintain a more predictable and manageable memory footprint.

    How to maintain data in an SQLite Database on an iPhone at a version update of the application?

    6 votes

    I have an SQLite database in the first version of my iPhone application (which is on the app store). Now I want to roll out the second version of the application, which also has an SQLite db in it.

    I understood that upon update, the SQLite database is removed and then the new one is added. I don't want this to happen, since that database holds some information that the user has saved. It wouldn't be good if it is deleted upon update.

    Question is, how do I transfer the data from the old SQLite (old version) database into the new one? And how can I test the version update process that would happen on the App Store?

    Any help would be greatly appreciated. Thanks.

    The answer is: implement versioning in your app from the very start :-)

    In this case, you can consider an app with no version information to be version 1. What I would do is store the version of the database somewhere (probably inside the database itself). When the database is opened, check its version against what version the app expects, then make any schema changes as needed and update the stored version number.

    If you haven't copied the database to the app's Documents directory, then this is all moot because it would be read only anyway. Otherwise, the contents of the Documents directory are preserved between updates.

    To test the update, just start with a fresh copy of the previous version on your device. Then install the new one (build and run will do just fine). You do keep old versions of your app, right?

    How do I store data securely with objective C? (Mac/Cocoa Dev)

    5 votes

    I'm trying to create a Trial part of my cocoa application. I have the licensing all set up (including keys) etc.

    But I was wondering how I could store e.g the first the time the user ran the program in a secure place, where the user can't easily find it and/or edit it.

    I was having a fiddle with NSUserDefaults standardUserDefaults, but the user can easily find and edit that data in Library > Preferences.

    I'd argue against making it super-secure. We once had a server activation but completely went away from it. Here are some of the reasons:

    • Even the most "secure" storage method can be broken
    • Even for a niche product a crack might be developed, no way around, no matter how secure your method
    • There are few, very expensive, very secure methods. All others have been cracked
    • It goes against fair and honest users, making it harder for them to fix things causing problems
    • If a user does crack your software or circumvents your security, he'll probably also never have bought it
    • 80% of the users don't even know what a preference file is
    • 95% of all users don't think of the possibility to delete it in order to extend the trial
    • A simple way to reset trial periods massively eases your support for users you want to give a second trial for whatever reason
    • Trusting users is a good selling point
    • Power users tend to turn against software with too much protection

    I'm pretty sure that there are some, but extremely few, exceptions from these thoughts. I'd say: don't waste your time on registration security but give

    Effect of 'myObj = [[[[MyClass alloc] init] autorelease] retain];' ?

    5 votes

    I've just downloaded the Facebook iOS SDK and I noticed that in the sample code that comes with the SDK whenever it creates an instance of the Facebook class it does it like this:

    _facebook = [[[[Facebook alloc] init] autorelease] retain];
    

    where _facebook is a member variable of the calling object (i.e. not a local variable).

    Can anyone explain exactly what's the point of autoreleasing and then retaining it?

    It effectively does nothing beyond consuming some cycles and memory.

    Or, more precisely, in a correctly written application, it does nothing. In an incorrectly written application, it might mask a bug by lengthening the lifespan of the _facebook object. However, it isn't a real fix.

    I found a similar line of code in http://github.com/facebook/facebook-ios-sdk/blob/master/sample/DemoApp/Classes/DemoAppViewController.m If that is what you are referring to then, yes, it is nonsense.