Saturday, September 13, 2014

Creating array of IBOutlet

Sometimes you want to enable/disable bunch of buttons together or perform other such activities on bunch of UI elements created using Interface Builder.

I recently needed to perform similar operation on bunch of button for iOS game I am working on. For this kind of operation, its easier to create array of IBOutlet which can be created using IBOutletCollection. Following is my code, which create IBOutletCollection of UIButtons and then enable/disbale them together.
@interface MyViewController : UIViewController {
    IBOutletCollection(UIButton) NSArray *buttons;
in MyViewController.m, we can use buttons as below.
-(void) enableUI:(BOOL) enable {    
    for( UIButton* button in buttons){
        button.enabled = enable;
Only thing missing now is, connecting UIButtons created using Interface Builder to IBoutletCollection. We need to do this from Interface Builder, process is similar to connecting UI Elements from Interface Builder to IBOutlet.

Following snaps describes the required process. I created three buttons on view.

You can connect IBoutletCollection to UIButton as shown in below snap.

And you can repeat above process to connect more UIButton with IBOutletCollection.

That's it.

Wednesday, September 10, 2014

Matching custom NSObject with isEqual and hash

While working on one multiplayer game for iOS using GameKit, I faced issue while comparing object.

For single player version I was not facing this issue but while running multiplayer version I was facing this issue. After debugging a little I realised condition for comparing object's value is failing and it turned out that I was comparing object's address rather then its value. As for Multiplayer game I was creating object using data from server/host, I needed to compare object's value and not its address.

For objectiveC, if you want to compare object's value using "==" operator, you need to overload isEqual and hash method as shown like below.

-(BOOL)isEqual:(id) other {
    if (other == self)
        return YES;
    if (!other || ![other isKindOfClass:[self class]])
        return NO;
    Card* otherCard = other;
    return ( mSuit == otherCard.mSuit && mRank == otherCard.mRank);

- (NSUInteger)hash {
    NSUInteger hash = 0;
    hash += [[NSNumber numberWithInt:mSuit] hash];
    hash += [[NSNumber numberWithInt:mRank] hash];
    return hash;
Note that you need to overload both method together, overloading only one will not work. Once I overloaded above method my multiplayer version started working as normal.