Xcode 4.3 Organizer Crash

April 4th, 2012

After downloading the new Xcode (4.3.2) I couldn’t get into the organizer’s Device Manager. Xcode crashed whenever I tried. It turns out that I had a few untrusted certificates in my keychain. This seems to be a problem for the new version of Xcode.

To remove them:

Applications/Utilities/Keychain Access (your default keychain should already be selected).

From the Category list select “Certificates” (/not/ “My Certificates”). Anything that doesn’t have the green checkmark next to “This certificate is valid” needs to go. /even self signed certs/

Restart Xcode and open the Organizer.

Presence 3 – Part 2 Custom Delegation

August 6th, 2009

Setting up a custom delegate seems pretty straightforward. In this case we want the calling class to understand what the child is saying to it.

I’ve set up my PersonListTableViewController with a toolbar item that allows me to update my twitter status. It does so by popping up a new modal window where I type in my status and hit done to send it over to twitter. Here’s where I do that. In the main view controller I add the method that will trigger my modal window. didTapEditStatusButton:

-(void)didTapEditStatusButton
{
StatusComposeViewController *statusComposeViewController = [[StatusComposeViewController alloc] init];
statusComposeViewController.delegate = self;

[self presentModalViewController:statusComposeViewController animated:YES];
[statusComposeViewController release];
}

The first thing that happens here is the modal window is instantiated.
Next I assign the delegate of the modal window to the main view controller. This is how we get the parent to listen to the child. Or, I guess this is where we tell the child who it’s daddy is.
When this is done all we need to do is present the controller, then release.

Because it is considered “Bad Form” for a modal window to dismiss itself, I’ll use delegation to let my parent view controller PersonListTableViewController know what the child view controller (my modal window) has done.

So the first thing I need to do is create my modal view. I’m going with the suggested StatusComposeViewController. Nothing new here, I’m subclassing UIViewController.

In the class header for my new view I need to add the delegation protocol. First thing I need to remember to do is declare the delegate protocol.
@protocol StatusComposeViewControllerDelegate;

Then I create the protocol and give it a couple of optional methods:

@protocol StatusComposeViewControllerDelegate
@optional
-(void)statusViewControllerDidSetStatus:(StatusComposeViewController *)controller didSetStatus:(NSString *)text;
-(void)statusViewControllerDidCancel:(StatusComposeViewController *)controller;
@end

This essentially declares these methods for whatever controller you specify as your delegate.

Moving back into my delegate (PersonListTableViewController) I’m going to need to implement the methods I’ve defined in my modal view. For this post I’ll just do one, the statusViewControllerDidSetStatus method.

-(void)statusViewControllerDidSetStatus:(StatusComposeViewController *)controller didSetStatus:(NSString *)text
{
[TwitterHelper updateStatus:text forUsername:username withPassword:password];
[self didFinishWithModalViewController];
}

A simple method for updating twitter status. The TwitterHelper class is provided in the course files. didFinishWithModalViewController is a method I’m using for cleanup and dismissal of the modal window. (Dismiss using [self didFinishWithModalViewController]). Any view can only have one modal view up at any given time, so we don’t need to tell this method which modal view to dismiss… it will always be the current modal view.

What did I miss…

Ok in the modal view controller StatusComposeViewController I need to implement the methods I’ll use to hit the delegate methods to perform the actions that the modal view is intended for.

- (IBAction)doneButtonPressed:(id)sender{
if([self.delegate respondsToSelector:@selector(statusViewControllerDidSetStatus:didSetStatus:)]){
[self.delegate statusViewControllerDidSetStatus:self didSetStatus:textField.text];
}
}

It is important to make sure you find out weather or not the delegate has implemented the method you’re going to try to call. This is done in the first line. Then we perform the operation.

Presence 3 (Part 1, Threading)

June 22nd, 2009

Mastering the art of threading using NSOperation is the first part of this assignment. I unfortunately got a bit stuck in the lecture examples. I was trying to implement the example code that I had seen without a solid understanding of what it was doing. This led to a few nights of frustration. I finally decided to scrap my currant process, go back to the code and try to really understand what it was doing. (I know, this is something one should always do, but in my zest to have a working prototype I lost sight of this).

My biggest problem here was that I needed to understand the order of operations a little better. The first thing I need my app to do is get the list of usernames. So, in my table view controllers initWithStyle method I read the names from the TwitterUsers.plist and initialize my names NSArray with the results.

//get the names
usersBundle = [[NSBundle mainBundle] pathForResource:@”TwitterUsers” ofType:@”plist”];
names = [[NSArray alloc] initWithContentsOfFile:usersBundle];

I’ll also use this method to init my NSOperationQueue. I’ll be needing this very soon.

In my viewWillAppear method I’ll call the method to get the list of details for each person. This is going to include the URLs for their respective images. Except, I don’t really call the method that does this. I call the method that adds the method that does this to an NSOperationQueue (getListOfPeople).

-(void)getListOfPeople
{
NSLog(@”(void)getListOfPeople”);
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(syncLoadingPeopleList) object:nil];
[operationQueue addOperation:operation];
[operation release];
}

So, syncLoadingPeopleList is the method that loads the people data into the people array. When this is finished I call the didFinishLoadingPeopleList back in the main thread.
[self performSelectorOnMainThread:@selector(didFinishLoadingPeopleList) withObject:nil waitUntilDone:NO];

The didFinishLoadingPeopleList iterates through the people and adds the image URL to my imageURLList NSMutableArray. Upon writing this, it occurs to me that I could probably just as well populate my imageURLList array in the syncLoadingPeopleList method at the same time I am populating the people array…

Here’s something that gave me some trouble initially. Chalk it up to a dumb mistake. At this point I still had my numberOfRowsInSection method looking at the size of my names array (perfectly ok in Presence 2). The problem here was that I was looking for information in my ImageURLList, which was populated by my people array, which at that point may not have had a single person loaded yet. I was getting all sorts of invalid index errors. Once I switched that out with the people array I was good to go.

So now I’ve got my image URLs, but still no images. Images need to be downloaded from the net and loaded into the table cell. Obviously this calls for some more threading. In my cellForRowAtIndexPath method where I would normally set my image to equal an already existing image, I’m setting it to equal the result of a cached image array lookup. Here’s how this works:

  1. cellForRowAtIndexPath is called nd wants an image
  2. image is set to the cached image
    cell.image = [self cachedImageForURL:[imageURLList objectAtIndex:indexPath.row]];

    • the cachedImageForURL method takes a NSURL as a param and looks to see if it’s NSMutableArray counterpart (cachedImages) already has this image
      id cachedObject = [cachedImages objectForKey:url];
      if(cachedObject == nil){
    • If so, then it checks to make sure it is an NSURL, and sets it to nil if not (remember it’s ok to send a nil message)
      else if(![cachedObject isKindOfClass:[UIImage class]]){
      cachedObject = nil;
      }
    • If not, then it starts the process of downloading the image
      ImageLoadingOperation *operation = [[ImageLoadingOperation alloc] initWithImageURL:url target:self action:@selector(didFinishLoadingImage:)];
      [operationQueue addOperation:operation];
      [operation release];
  3. This executes as many times as there are people in the list, and calls didFinishLoadingImage as soon as the image is loaded and ready for use. This adds the image to the cashedImages array and reloads the table data.
    -(void)didFinishLoadingImage:(NSDictionary *)result
    {
    NSURL *url = [result objectForKey:@"url"];
    UIImage *image = [result objectForKey:@"image"];

    [cachedImages setObject:image forKey:url];
    [self.tableView reloadData];
    }

…and we have our image

Threading intro

June 15th, 2009

While my app grabs data from the net I want the user to see a loading animation. To do this I need to break off the main thread and start a new one for the net load, and use the main thread to display the animation. I’ve set up my load animation using a nib, though this is simple enough to where I’d probably prefer to just do it programmatically. But that’s not really what I care about right now. Anyway, my nib is called “LoadSpinner”, and the controller is called “LoadSpinnerController”. Simple first step is to load this view (it subclasses UIView) and add it to the application view. Easy enough, done this quite a few times now:

spinnerController = [[LoadSpinnerController alloc] initWithNibName:@”LoadSpinner” bundle:nil];
[window addSubview:spinnerController.view];

Next I want to start the loading process, so I detach a new thread from the main thread like so:
[NSThread detachNewThreadSelector:@selector(loadNetInfo) toTarget:self withObject:nil];

where loadNetInfo is the method used to grab whatever data I need. Outlined here:

-(void) loadNetInfo
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

doing the loading stuff here..

[self performSelectorOnMainThread:@selector(releaseSpinner) withObject:nil waitUntilDone:NO];
[pool release];
}

Notice the selector is looking for releaseSpinner. I don’t know if this is the best way to do it, but all I’m doing in this method is [spinnerController release];. This gets rid of the spinner when the info is returned, loaded and ready for use. I’ll have to see if there’s a better way to do this.

Presence 2

June 10th, 2009

I found cell rendering to be the biggest challenge in this assignment.

The process of making this work is a bit drawn out. The first thing I need to do is calculate what my rowHeight needs to be. This is done by overriding the heightForRowAtIndexPath method in my TableViewController.

  1. Grab the string that needs to fit in the cell.
  2. Set its font size.
  3. Create a CGSize object using my cell width (I used a static width in this case) and a max hieght of 1000 (hopefully I wouldn’t need more height than that). This is done using CGSizeMake(280, 1000);
  4. Assign it a size based on the font, font size, and line break mode
  5. Then return the height, with a bit of padding return size.height + 20;

Once the row height has been calculated I init my label with a CGRect that specifies the label size based on the dimensions of my cell, then I add it to the contentView of the cell.
Now in order to make the label multiline enabled I first need to specify the numberOfLines property. I’m setting it to equal 0. This means that I’ll get as many lines as needed to fit the text (I don’t know exactly why this works the way it does. I could also put it some arbitrary number, and it would still work, but the maximum number of line breaks would be limited by that number). Then I need to set the autoResizingMask property of my label to UIViewAutoresizingFlexibleHeight. Also, I have to make sure I’m using the same font and font size that I specified in the heightForRowAtIndexPath method (setFont:[UIFont systemFontOfSize:14.0]). The it’s just a matter of setting the text value, adding it to the cell and releasing it.

Presence 1

May 28th, 2009

We need create an app that subclasses the UIViewController class. What is supposed to happen essentially is that we should hit a button and navigate to another window. Eventually multiple buttons will take us to different windows. I was initially feeling inspired by my new found confidence in my understanding of InterfaceBuilder. That all came crashing down when I tried applying some new concepts (loading views dynamically). It’s really not all that complex, just more so than I was initially prepared for.

Starting with my applicationDidFinishLaunching method (in my delegate):

// init the navigation controller (don’t mistake for a view)
navigationController = [[UINavigationController alloc] init];

// instantiate the first view controller (bottom of the stack)
PersonListViewController *listViewController = [[PersonListViewController alloc] initWithNibName:@”PersonListView” bundle:nil];

// push the view controller to the navigation controller
[navigationController pushViewController:listViewController animated:NO];

// the navigation controller now owns the view, let the copy go here
[listViewController release];

// add the navigation controller to the display
[window addSubview:navigationController.view];

// Override point for customization after application launch
[window makeKeyAndVisible];

I’m initializing my navigation controller here first (as opposed to doing it in the nib). Then I init my first view controller. This is going to be the default view for my navigation controller and is going to live on the bottom of the view stack (first on, last off).

Once I’ve pushed my PersonListView to my UINavigationController I’m done with it and can release.

From there I just need to add navigationController to my window and make it visible.

Adding another view

What I need to remember here is that this is calling it’s own nib (initWithNibName). I need to create this nib file, then I need to specify my PersonListViewController class as the File’s Owner, otherwise I get the following error (when trying to load the nib I called PersonListView:

loaded the "PersonListView" nib but the view outlet was not set.

The File’s Owner is an object proxy. The reason for the File’s Owner (as I have come to understand it after reading this thread) is basically to let objects that are currently loaded into your app know about objects that haven’t quite loaded yet so that objects your existing nib have a reference to those pre-existing objects.

Maybe this is a bit of a stretch, but I liken it to the english word “thing” (bear with me). I often use “thing” when I’m unable to immediately recall the actual name of the object I’m referring to. “Thing” is a placeholder while I flesh out the rest of my sentence.

Simply designating my PersonListViewController as the File’s Owner doesn’t get rid of this error though. I need to connect the view object in my nib to the view outlet in my UIViewController subclass (PersonListViewController).

With that figured out I can move on to the navigation part of the assignment. In my PersonListView nib I create a button that I’ll use to trigger the move to the next view in the stack, and the action that handles the button click.
Then I create a new class that subclasses the UIViewController (just like my PersonListViewController) and call it PersonDetailViewController. When the button in PersonListView is clicked I add this view to the stack by pushing the new view to the navigationController:

PersonDetailViewController *personDetail = [[PersonDetailViewController alloc] initWithNibName:@”PersonDetail” bundle:nil];
[[self navigationController] pushViewController:personDetail animated:YES];

A few things to note:

  • Dynamically loading and displaying an image:
    This was interesting. I initially concocted this (the uImage value was set to “mug.jpg” which exists in my main bundle):

    NSData *imgData = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@", [[people objectAtIndex:user] uImage]]];
    UIImage *diasplayImage = [UIImage imageWithData:imgData];
    uImage.image = diasplayImage;

    I couldn’t figure out why it didn’t work, until I read more of the documentation. the dataWithContentsOfFile method in NSData expects an absolute path to the image. As soon as I gave it “/Users/me/absolute/path/to/mug.jpg” it worked like a charm. I’m going to have to learn more about the iPhone filesystem, but for this app, loading an image this way isn’t really what I want. I’d rather just grab the image relative to my main bundle. I do this like so:

    uImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",[[people objectAtIndex:user] uImage]]];

    imageNamed looks first in the cache for the image. If it doesn’t find it there it will look in my main bundle, cache it, then display it.

  • Don’t forget to link the UIImageView object (in the nib) to my “File’s Owner” uImage outlet.
  • I’m using the tag property of each button in my PersonListViewController to tell my PersonDetailViewController which button was pressed (which user was selected)

Assignment 3

May 26th, 2009

I was having a very hard time with this one. My problem was that I still didn’t fully understand the relationship between XCode and Interface Builder. I’m not saying I know it all now, but I think I’m closer.

I had been struggling with the seeming lack of instantiation for my controller. I couldn’t find anywhere in my generated code (i.e. code created after dragging an object into my nib file window, setting up outlets, actions, etc, and selecting File>Write Class Files) where my Controller class was being instantiated. I wanted to assume that the nib takes care of this, well, it does, or, I do. By virtue of dragging the object into my nib window and assigning a class to it I am instantiating that class (it’s all spelled out for me right there in the description of the object, I missed it initially).

This helps to allow connections to make more sense to me. Once I got past the hocus pocus of magical object instantiation, I could look at connections more simply, as just connections, not some nebulous directive to instantiate as well. This had me thinking though. I was initializing my PolygonView class in my controller’s init method. It didn’t seem in keeping with my theory that interface builder takes care of instantiation, so I pulled the polygon init code out of my controller class to see how far south things would go. My code compiled without a problem, and my app ran just as well as before, except better, because now I wasn’t wasting memory instantiating an unused object.

My controller class keeps track of my view(s) and model(s). Within my controller I set up instance vars. I use interface builder to point them to the objects they represent.

Just to get this to sink in a bit more I played around with multiple instances of my PolygonView class. Adding a couple more poly view objects for a preview of the next and previous polygons.

Assignment 2B – HelloPolly (Part I)

May 24th, 2009

I’m revisiting this assignment and I think I originally blocked out most of what the walkthrough was trying to explain. At this point there is still a whole lot for me to learn about IB, but after getting as far as assignment 8 and still being confused by IB’s role this was a good refresher.

InterfaceBuilder can write class files for you based on actions, outlets and connections you specify. Though the connections don’t ever seem to be apparent in the code (at least not in a way that I could term as meaningful). This has proven to represent the biggest challenge for me. I like to see everything that’s happening in my code.

I need this to sink in.

Let’s say I have two buttons and a label in my window, setting up a controller class goes like this:

  • Drag an Object to my nib file window
  • Select the object and name the class whatever I want my controller to be called
  • Add some outlets that correspond with my two buttons and label, and actions as needed (so that my buttons will do something when tapped)
  • Connect the controller outlets to the UI elements in the window
  • Point the buttons to their respective actions like this:
    • Select the button of interest
    • in the connections inspector select whatever action I like (ex. touchUpInside)
    • Drag the action (using the connection circle to the right of the action) to my controller object in the nib window and let go
    • Select the appropriate action method in the controller (action methods will appear in a pop-up)

This is pretty much it. The walkthrough for the assignment goes into quite a bit of detail and more or less does it all for me. Just remember, create the controller object in IB and write class files from there. Link it up to the model class(es) by assigning my models to their own objects in IB, and pointing the controller at them (control+click, drag, release). This can actually be a bit deceiving. I select my controller and drag the connection over to my PolygonShape class and the polygon iVar within the controller appears in the pop-up. I would have expected the pop-up to contain vars associated with the PolygonShape class.

Assignment 2A – Custom Class

May 24th, 2009

In this assignment we created a custom Polygon class. Goals were to:

  • instantiate with a default number of sides as well as a specified number of sides.
  • Increment, decrement the side count.
  • Calculate the angle in degrees and radians.
  • Set min and max number of sides (and restrict incremental and decremental methods from exceeding those bounds)
  • Give the polygon a name (read only) that is updated when the number of sides it has changes
  • play with dealloc for a hands on introduction to memory management

So, first thing I need to remember is that when synthesizing iVars the getter and setter methods are made available (even though I never see them in code). The naming convention for these is pretty standard. If I synthesize an iVar (instance variable) called “numberOfSides”, I will have gained access to the getter (numberOfSides) and setter (setNumberOfSides) methods.

Synthesizing is a convenience. It means I don’t have to write setters and getters for every little iVar I declare unless I want to do something special when setting the values.

In the case of this assignment, I actually do want to do something special when setting the number of sides for the polygon. I need to make sure that if the given number of sides is greater than max, or less than min, I don’t update, rather I throw an exception (or a suitably graceful error). So I implemented my own setter methods for these operations. I can still synthesize even if I choose to later implement my own methods. My custom methods will just override the synthesized ones.

Syntax for this has two parts. Obviously I need to declare the var in my interface

@interface PolygonShape : NSObject {

(int) numberOfSides;

}

// to synthesize this var I first need to define it as a property:

@property int numberOfSides;

I synthesize it in my implementation file:

@synthesize numberOfSides;

Know thy self

Another thing to note is that “self” == “this” (as it would be in Actionscript, php, Java, etc…)
So, in Obj-C I’d write:

[self setMaximumNumberOfSides:12];

Where in Actionscript it would be:

this.setMaximumNumberOfSides(12);

Method Syntax

I’m also having a hard time getting the method syntax to sink in. Proper syntax is:
[receiver message:arg]
where receiver is the object, message is the method to call on that object, and arg is the argument to send.

So, I have a polygon object and I want to initialize it with a number of sides defined by me, along with min and max side constraints. Here’s what that looks like:

Polygon *poly = [[Polygon alloc] initWithSides:5 minSides:3 maxSides:12];

Now my polygon object instance “poly” has an instance method called “incrementSides” that increments to number of sides by whatever value I pass to it. If I want to add 3 sides to my polygon I’ll do this:

[poly incrementSides:3];

Assignment 1B : “WhatATool Part I”

May 22nd, 2009

I made myself familiar with some Obj-c syntax here, as well as basic app structure. Things a complete novice (such as myself) should keep in mind:

NSString

To create an NSString:

NSString *myString = @”This is my new NSString”;

To output different types within my string I need to use stringWithFormat, and the right format specifier to define that type. For example, I can’t assign an integer type as part of an NSString. The full list of specifiers is• here. Here are the specifiers I’ve most commonly used:

  • %@: Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise. Also works with CFTypeRef objects, returning the result of the CFCopyDescription function.
  • %d, %D, %i: Signed 32-bit integer (int)
  • %u, %U: Unsigned 32-bit integer (unsigned int)
  • %f 64-bit floating-point number (double)

The format for using these is:

NSString *myString = [NSString stringWithFormat:@"Here is an int:%d, and an Object:%@", 42, myObject];

I can append a string using the aptly named stringByAppendingString :

NSString *beginString = @”The quick brown fox”;
NSString *nextString = @” jumped over the lazy dog”;

NSLog([beginString stringByAppendingString: nextString]);

which will output:

“The quick brown fox jumped over the lazy dog”

to the console.

NSDictionary

There are a lot of ways to get values into an NSDictionary. The API reference is a great place to look for details about that. For this assignment I used dictionaryWithObjects:forKeys

I created key objects and stuffed them into an array:

NSString *firstString = @”Stanford University”;

NSString *secondString = @”Apple”;

NSArray *keyArray = [NSArray arrayWithObjects:firstString, secondString, nil];

(There was some initial frustration here because I didn’t realize that when populating/creating an array this way I needed to terminate the array with a nil value so that arrayWithObjects knows that it has reached the end of the array. Not necessary with other types of instantiation)

then value objects:

NSURL *firstURL = [NSURL URLWithString:@"http://www.stanford.edu"];
NSURL *secondURL = [NSURL URLWithString:@"http://www.stanford.edu"];
NSArray *valueArray = [NSArray arrayWithObjects:firstURL, secondURL, nil]

…and into the Dictionary they go:

NSDictionary *myDict = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];

Enumerator:

(assuming obj1 – obj5 have been created…)

NSMutableArray *lotsOfObjects = [NSMutableArray arrayWithObjects:obj1, obj2, obj3, obj4, obj5, nil];

carve out a space for the enum:

NSEnumerator *en = [lotsOfObjects objectEnumerator];

and give it something to store the iterated object’s value in (id is a generic object type (for lack of the desire to go looking for a better description right now))

id obj = nil;

then use it:

while (obj = [en nextObject]) {

//do something with obj

}