Showing posts with label iOS 5. Show all posts
Showing posts with label iOS 5. Show all posts

Monday, June 24, 2013

Hidden Gems in Cocoa Touch / XCode

1. Open Quickly (Command-Shift-O)
2. View Related Files From Toolbar
3. Use breakpoint actions such as log message or play a sound to avoid recompiling.
4. Use debugDescription.
5. Use Objective-C Subscripting.
NSMutableArray *indexedValues = [NSMutableArray array];
indexedValues[0] = @"One";
NSLog(@"value: %@", indexedValues[0]);
NSMutableDictionary *keyedValues = [NSMutableDictionary dictionary];
keyedValues[@"color"] = [UIColor blueColor];
NSLog(@"value: %@", keyedValues[@"color"]);
6. Private declarations not necessary since Xcode 4.3
7. Synthesize not necessary for @property since Xcode 4.4
8. Reverse arrays quickly inline

 NSArray *numbers = @[ @1, @2, @3 ];
 NSArray *reversed = numbers.reverseObjectEnumerator.allObjects;
9.  Guarantee a mutable object

 NSArray *unknown = self.values; // may be nil
 NSMutableArray *newArray = [NSMutableArray arrayWithArray:unknown];
10. Declare and enumerate different collection types

 id collection = values;
 for (id object in collection) {
... }
11. Remove duplicate values in array without NSSet

[array valueForKeyPath:@"@distinctUnionOfObjects.self"]
12. CAGradientLayer

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(150, 250, 500, 500);
UIColor *c1 = [UIColor colorWithRed:0.09 green:0.70 blue:0.98 alpha:1.0];
UIColor *c2 = [UIColor colorWithRed:0.07 green:0.41 blue:0.95 alpha:1.0];
UIColor *c3 = [UIColor colorWithRed:0.81 green:0.46 blue:0.93 alpha:1.0];
gradient.colors = @[(id)c2.CGColor, (id)c3.CGColor, (id)c3.CGColor];
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"colors"];
anim.toValue = @[(id)c1.CGColor, (id)c2.CGColor, (id)c2.CGColor];
anim.duration = 4.0;
anim.autoreverses = YES;
anim.repeatCount = 1e100;
[gradient addAnimation:anim forKey:@"colors"];
[self.view.layer addSublayer:gradient];

13. Core Data Private Queue

NSManagedObjectContext *bgContext;
bgContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:
                                    NSPrivateQueueConcurrencyType];
[context performBlock:^{
    // (add, remove, change objects.)
    saveCompleted = [context save:& saveError];
}];

14. Core Data
Really fast fetches
• Only specific properties

 NSFetchRequest
 fetch.propertiesToFetch = @[@"name", @"phone"];
• Only the raw values

fetch.resultType = NSDictionaryResultType 
• Only the object id

 fetch.resultType = NSManagedObjectIDResultType
• Only the count

 fetch.resultType = NSCountResultType

Tuesday, October 25, 2011

iOS 5 Storyboard + UITableView Tutorial II (Improved)

Since I'm learning as well and have been reading other people's tutorials that I thought were not very good (because they either had too much clutter or did not stress the important points) I thought I would make another tutorial on the key ideas of UITableViews that I missed out on before.

Download Project: here.
1. Create a new Tabbed Application called StoryboardUITableView.



2. In the MainStoryboard file look at the attribute inspector and you will see the checkbox for Is Initial View Controller.

Common Error: Not having set an initial view controller. The simulator will popup and then just be in a deadlock and in the output log, it will say something about how your application doesn't not have a root view controller.



3. Embed a navigation controller in the first view by going to Editor > Embed In > Navigation Controller.

Note: If you delete the connection, and then control+drag from the Tab Bar Controller you will see the following in the image below. You can set the initial scene to be the first view controller by control + dragging as described before and then selecting Relationship - viewControllers. This creates a connection between the Tab Bar Controller and and Navigation Controller.




4. Suppose I create a tableview by drag and dropping it a UITableViewController, I can customize the cells in the right panel.

Key Points:

Style: Change Style of UITableViewCell
Identifier: Cell Identifier to Distinguish Prototype Cells
Accessory: The Creates The Right Facing Arrow
Size: Resize the cell by dragging it up or down.

Note: Ignore the left half of the screenshot since I made an error the first time.


5. Create a new UITableViewController called AlbumViewController and select the table view controller and change its class to AlbumViewController .




6. Suppose I created a datasource in the AppDelegate.m file and I follow the usual steps to populate the tableview. The one interesting change is here: tableview cells are now automatically allocated so the code is much simpler than before. In the AlbumViewController.m file implement the usual methods.

 (Note: Copy and paste them from the source file in the download.)


7. Change this method and you can then slide to delete a tableview cell.




8. Run and project and it will turn out like this.


Download Project: here.

http://kurrytran.blogspot.com/2013/06/fast-scrolling-customized-uitableviews.html

Monday, October 24, 2011

Example Project: Creating a TwitPic Replacement with the Twitter Framework in iOS 5

I was doing research into different Twitter iPhone apps to determine what people liked about each one and I stumbled upon (and purchased) the TwitPic app. I realized that you can easily create a similar app using the Twitter Framework in iOS 5. I don't have time for a step-by-step tutorial right now, but I provided the entire project for download here.












Project Available to Download: here.

Note: I do not own any of the Twitter pictures and I am in no way affiliated with Twitter.

Note: The project isn't "finished" yet, but it's a good starting point.









Example Project: Using iOS 5 Twitter API to Find Foursquare Checkins (Unfinished)

Download Project: here









Sunday, October 23, 2011

iOS 5 Tweeting Apple Sample Code (Errors?) + How to Parse JSON With NSJSONSerialization

     I was planning on creating an extensive tutorial a couple weeks ago on how to use the Twitter API in iOS 5, but I was running into errors and I thought I would tell you what my errors were and how I resolved them.

Apple Sample Code: here

1. I downloaded the Tweeting Apple sample code and ran the package and noticed they had an example on how to download public timelines in JSON format using the new TWRequest class.


2. In the sample code they used the NSJSONSerialization to create the publicTimeline NSDictionary. I tried to create a new array NSArray *keys = [publicTimeline allKeys]; and the program would crash.

This is the error:





3. Naturally, the first thing I did was ask my friend who works at Apple (comparative advantage) and he really didn't know what was going on so I was stuck and trying different things for about a week. I then did some searching and reading in forums and someone was having a similar error with NSMutableArrays being converted into NSCFArrays and then someone on stack overflow suggested creating a new array with an array and it sparked an idea for me to do the same.

Note: I searched the Apple Developer Forums as well and I couldn't find a solution so I thought I should post it here.


4. Anyways, long story short I figured out how to do it. Just create an array with the publicTimeline NSDictionary. Each object in the NSArray is an NSDictionary of statuses and using the key "text" you can retrieve the text of each tweet.






I have to finish this post later since I have midterms this week...  In the meantime you can download the project below.

Full Project Here: here

Correction: What you can do is just create an array initially.



Wednesday, October 19, 2011

iOS 5 Storyboard and UITableViews Tutorial

In this tutorial we will:

1. Create a UITableView from scratch.
2. Learn about navigation controllers.
3. Pushing view controllers with storyboard.

Link to Download Entire Project: here

1. Create a new single view based application called "StoryboardTutorial".


2. Select the main storyboard file and then select Editor > Embed In > Navigation Controller.
Note: A navigation controller is a way to manage views. Typically you push or pop a view onto a navigation controller. You can think of this a stack.


3. Next drag and drop a UITableView from the right sidebar and place it onto the view controller.


4. Go into the ViewController.h file and add after it says UIViewController. This tells the compiler that your class will conform to the UITableViewDelegate/UITableViewDataSource protocols. A protocol is just a formal way of saying that you will implement all methods that are required so you have a functioning tableview. 




Note: The biggest benefit of declaring the ViewController.h object as such is that now Xcode will autogenerate code and most of your necessary methods you would like to implement in the tableview class. Also note, if the method is not auto-generating you're probably doing something wrong. That's the main way I know I'm doing something wrong, or the program crashes.



5. Go back to the main storyboard file and "Control + Drag" from the tableview to the view controller and select "data source" and "delegate". This is how you tell the tableview where it is going to get it's data from, and if an event (a touch event for example) happens, who should it notify.


6. Now click on a tableview cell and click on the right side bar and go to the fourth panel from the left. In the field Identifier type "Cell". This is label so that you can reuse tableview cells which saves memory.


7. In the ViewController.m file implement these protocol methods.
Note: Philosophically it would make sense that you would needs to implement these methods to have create an actually tableview. You need to know 1) how many rows should you have and 2) what should you label these rows and 3) what to do when a user clicks on it.

Debugging Tip: Manually label the cells at first to make sure you made your connections correctly. I once spent three hours of my life trying to figure out why my tableview was empty. Save yourself the misery.



After you implement those methods it should look like this. I changed the table to states because I wanted to later show how to alphabetize a list of states.


8. Go back to the main storyboard file and drag and drop a View Controller object, and in the right panel type "detail" and the Identifier. This will be the detail view controller to push another view onto the view controller.


9. Go to File > New File > UIViewController Subclass and then create a UIViewController subclass called "DetailViewController" and unselect use XIB for interface.



10. Go back to the main storyboard file and in the right panel change the class of your newest view controller to be the "DetailViewController" that you just created.


11. Now go back to the ViewController.h file and then add "#import DetailViewController.h" at the top of your file. Then edit the two methods like below.

Note: What's new in iOS 5 is the storyboard and transitioning from one view to the other. Instead of having lots of Xib files, you replace them with views all placed into one storyboard file. This makes life much easier for the developer. So seen below is how you create a view controller object in storyboard.
"[self.storyboard instantiateViewControllerWithIdentifier:@"detail"" tells the computer to create the view that I called "detail" in the storyboard file, and then the "[self.navigationController pushViewController:detail animated:YES]" then pushes the view onto the view stack, so the visible view is then the current view.

Note: The tableview height method is self-explanatory. For some reason I had a hard time finding that method when I first started so I thought I would include it here for people to play with.


If everything is working correctly you should see these two screens if you select onto a tableview cell.

Note: In keeping with the states them I added two label to the detail view to work with later on.




12. Now if you can add a background image to the tableview cell by editing the cellForRowAtIndexPath method. Here I have a 320x65 pixel image called "LightGrey.png" which I'll include in the project at the end of the tutorial. Adding a background image really adds vibrance to your tableview.





13. Create a datasource by editing your ViewController.h and ViewController.m files so they match the ones below.
















Then make these changes in the ViewController.m file:



Changes:
1) @synthesize states and datasource.
2) In the viewDidLoad method call the function setupArray;
3) Create the datasource in setupArray;
4) Change the text label so that it reads from the datasource.

14. Edit the DetailViewController.h file so it matches the one below.



Then @synthesize them at the top of the DetailViewController.m file.


Then edit the viewDidLoad method.


15. Go back to the main storyboard file and select the detail view controller and "Control + Drag" from the DetailViewController to each of the UILabels and connect them to the appropriate outlet. 








16. Then go back to the ViewController.m file and edit the didSelectRowAtIndexPathMethod so it matches the following. This is just passing data from one view to the other.

So now when you select the state, the detail view will show the state's name and the state capital.