Cocoa-Matic

iPhone, iPod touch, iPad tutorials, examples and sample code. Come and get it!

Thursday, January 12, 2012

SQLite import from .csv file

Here are the quick and easy steps to import the contents of a .csv file into your SQLite3 database.

Open the db via the command line:
sqlite3 myDatabaseName

Enter the following commands:
.separator ","
.import myFile.csv tblMyTable


And that's it.  If your .csv file has a different separator character, just replace the comma with your character.

Wednesday, January 26, 2011

XCode Linker error: Symbol(s) not found

Came across a weird error today:

Objc-class-ref-to-[ClassName] in MainController.o
Symbol(s) not found
Collect2: Id returned 1 exit status

For some reason the reference to the class in question is not listed under Compile Sources. Thankfully, it's an easy fix.

1. Under Groups & Files, expand Targets
2. Expand the compile target
3. Expand Compile Sources (xx)
4. Check to see if all of your .m files are listed. If not, drag the missing files in.
5. Recompile and run.

So, not sure why this happens, but luckily there's an easy fix.

Labels: ,

UITextField horizontal and vertical alignment

Horizontal alignment in a UITextField was quick and easy to find:
myTextField.textAlignment = UITextAlignmentLeft;
myTextField.textAlignment = UITextAlignmentCenter;
myTextField.textAlignment = UITextAlignmentRight;

Vertical alignment in a UITextField is equally as easy, just a little harder to find:
myTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
myTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
myTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
myTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;

Enjoy!

Labels: , , ,

Wednesday, January 12, 2011

Replace UINavigationBar background with image

Sometimes you want to show off some creativity in your apps. One of the easiest ways to do that is by changing the look of the UINavigationBar. Modifying the color is one way and is a trivial task in Interface Builder. What about replacing it entirely with an image? Turns out that's not too difficult either. Here's how...

We're going to use Categories. What are Categories?
From CocoaDevCentral.com: Categories are one of the most useful features of Objective-C. Essentially, a category allows you to add methods to an existing class without subclassing it or needing to know any of the details of how it's implemented.

This is particularly useful because you can add methods to built-in objects. If you want to add a method to all instances of NSString in your application, you just add a category. There's no need to get everything to use a custom subclass.


Read more »

Labels: , , ,

Wednesday, September 1, 2010

NSDate number of days between two dates

Date objects in programming are typically both extremely common and notoriously tricky due to the many different syntaxes involved. These rules apply to iPhone development. In one application I created, I needed the number of days between 2 dates in several instances. As there is no simple NSDate2 - NSDate1 function built-in to return the number of days apart, I wrote a function to accomplish the task. Here it is...
Read more »

Labels: , , , , ,

Friday, August 20, 2010

Create UIPickerView programmatically

The UIPickerView is one of the input controls in iOS for displaying and selecting a list of data. Most tutorials implement this control in Interface Builder, which is fine, but I like to have more control and do most everything in code. There are several components to doing this 100% programmatically, which I will demonstrate below...

The first thing we have to do is include the UIPickerViewDelegate in the interface of our class .h file.
@interface myViewController : UIViewController<UIPickerViewDelegate>
Read more »

Labels: , ,

Wednesday, August 18, 2010

Prevent UITableView from scrolling

Quick tip:

UITableView elements enable vertical scrolling by default. The following code disables the scroll:
myTableView.scrollEnabled = NO;

Labels: , , ,

Tuesday, August 17, 2010

Random Number in Cocoa and Objective-c

Generating a random number is fairly simple using arc4random(). Say you want a random integer between 10 (min) and 1000 (max). Here's how to do it:

int max = 1000;
int min = 10;
int value = (arc4random() % max) + min;

Also, no need to do any seeding with this method.

Labels: ,

Friday, August 13, 2010

Unwanted UITableView gray background on iPad

I came across something weird when developing an iPad app. I have a UITableView that does not encompass the entire screen and I have it set to grouping mode so it has nice looking rounded corners. For some reason when this is displayed, the background of the UITableView is light gray. It seems to be ignoring the backgroundColor property.

So, here's the fix:
Read more »

Labels: , , ,

Asynchronous data request class

A very handly class I've built is asyncDataRequest. This provides for an easy way to make and receive calls to web data feeds. All you have to do is include the class reference in your .m file, make the request and create a notification responder to receive and parse that data response.

First, we'll look at asyncDataRequest.h:
@interface asyncDataRequest : NSObject {
 NSMutableData *responseData;
 id delegate;
 NSString *notificationName;
}

@property(nonatomic,retain) NSMutableData *responseData;
@property(nonatomic,assign) id delegate;
@property(nonatomic,retain) NSString *notificationName;

- (void)setDelegate:(id)newDelegate;
- (void)connection:(NSURLConnection *)connection didReceiveResponse: (NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connection:(NSURLConnection *)connection didFailWithError: (NSError *)error;
- (void)connectionDidFinishLoading: (NSURLConnection *)connection;

@end

Read more »

Labels: , , , ,

Thursday, August 12, 2010

UIButton with custom UIImage

Most developers want to steer clear of the default buttons provided in Cocoa because they're just not that attractive. The following code shows how to programmatically create an image button and define an action for when the button is pressed.
// Create button and set frame
UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
// Set button image, in this case "my_image.png"
[myButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"my_image" ofType:@"png"]] forState:UIControlStateNormal];
// Call buttonWasPressed function when button is touched
[myButton addTarget:self action:@selector(buttonWasPressed) forControlEvents:UIControlEventTouchUpInside];
// Add the button to view
[self.view addSubview:myButton];

Labels: , ,

Thursday, August 5, 2010

UILabel dynamic sizing based on string

Here's how to create a UILabel that dynamically resizes to fit the NSString that is loaded into it:
UILabel *tmpTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 20)];
self.titleLabel = tmpTitleLabel;
[tmpTitleLabel release];
self.titleLabel.textColor = [UIColor blackColor];
self.titleLabel.font = [UIFont boldSystemFontOfSize:16];
self.titleLabel.numberOfLines = 0;
self.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
self.titleLabel.text = self.myTitleString;
 
//Calculate the expected size based on the font and linebreak mode of label
CGSize maximumLabelSize = CGSizeMake(300,9999);
CGSize expectedLabelSize = [self.myTitleString sizeWithFont:self.titleLabel.font constrainedToSize:maximumLabelSize lineBreakMode:self.titleLabel.lineBreakMode];
 
//Adjust the label the the new height
CGRect newFrame = self.titleLabel.frame;
newFrame.size.height = expectedLabelSize.height;
self.titleLabel.frame = newFrame;
And here's the explanation of what's going on with this code:
Read more »

Labels: , , ,

Wednesday, August 4, 2010

Better NSLog implementation

NSLog is an invaluable tool for developers who are looking to debug and/or troubleshoot code. It outputs to the debugger console during the application runtime. Before I show a better way to use the NSLog function, let's go over the basics with an example:

int myInt = 100;
NSLog(@"The value of myInt: %i", myInt);
This will output:
The value of myInt: 100

Depending on what type of value you're trying to print, you'll have to use different Format Specifiers (%i in the previous example). Here's a list of common Format Specifiers:
Read more »

Labels:

Tuesday, August 3, 2010

UITextField: Only allow numeric entry using NSScanner

Have a UITextField and want to prevent the user from entering anything but numbers (and decimal point)? This quick function utilizing the UITextFieldDelegate will do the trick.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

 NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
 
 // This allows backspace
 if ([resultingString length] == 0) {
  return true;
 }

 double holder;
 NSScanner *scan = [NSScanner scannerWithString: resultingString];
 
 return [scan scanDouble: &holder] && [scan isAtEnd];
}
Read more »

Labels: , , ,

Friday, July 30, 2010

UIColor macro with hex values

Cocoa has several colors built into the UIColor class. For example:
[UIColor redColor];
[UIColor darkGrayColor];

This is great, but what if you want one of the thousands of colors not found in the pre-defined list? There's an easy way to do that:
[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];

Perfect. But what if you just have a list of hex color codes? Wouldn't it be nice if you didn't have to convert each of the color components in the hex code to its corresponding RGB decimal value? Here's where a simple and very useful macro comes into play. Just place the code below in a header file and you're done. (They're identical except that UIColorFromRGB always sets the alpha value to 1.0, whereas UIColorFromRGBWithAlpha allows you to set the alpha value.)
Read more »

Labels: , , ,

Creating UIViews programmatically

If you want to create a new UIViewController object without using a Nib file in Interface Builder, you must use the loadView method. It's rather simple, but key to doing things programmatically.
- (void)loadView {
 CGRect viewFrame;
 viewFrame = CGRectMake(0, 0, MASTER_WIDTH, MASTER_HEIGHT);
 self.view = [[[UIView alloc] initWithFrame:viewFrame] autorelease];
}
(Note: MASTER_WIDTH and MASTER_HEIGHT are simply constants defining the width and height of the screen.)

Once your view is created, you are free to implement, as usual, viewDidLoad, viewWillAppear, viewDidAppear, etc.

Labels: , , ,

Thursday, August 13, 2009

Add decimal point to number pad

Add this to viewDidLoad:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShowWeight:) name:UIKeyboardDidShowNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowWeight:) name:UIKeyboardWillShowNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHideWeight:) name:UIKeyboardDidHideNotification object:nil];


Add these methods:

- (void)addDecimalPoint:(id)sender {

NSLog(@"decimal point pressed");

BOOL allowDecimal = YES;

unichar c;

unichar d = '.';

for(int i=0;i<[todayWeighInTextField.text length];i++) {

c = [todayWeighInTextField.text characterAtIndex:i];

if(c == d) allowDecimal = NO;

}

if(allowDecimal) todayWeighInTextField.text = [todayWeighInTextField.text stringByAppendingString:@"."];

}


- (void)keyboardDidShowWeight:(NSNotification *)note {

[self.keyboardToolbar setHidden:NO];

}


- (void)keyboardWillShowWeight:(NSNotification *)note {

UIWindow *tmpWindow;

UIViewController *mainViewController = self;

UIView *keyboard;

for(int i=0;i<[[[UIApplication sharedApplication] windows] count];i++) {

tmpWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:i];

for(int j=0;j<[tmpWindow.subviews count];j++) {

keyboard = [tmpWindow.subviews objectAtIndex:j];

if([[keyboard description] hasPrefix:@"] == YES) {

UIButton *decimalPointBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

decimalPointBtn.frame = CGRectMake(0, 164, 106, 53);

[decimalPointBtn setImage:[UIImage imageNamed:@"decimalPointNormal.png"] forState:UIControlStateNormal];

[decimalPointBtn setImage:[UIImage imageNamed:@"decimalPointPressed.png"] forState:UIControlStateHighlighted];

[keyboard addSubview:decimalPointBtn];

[decimalPointBtn addTarget:mainViewController action:@selector(addDecimalPoint:) forControlEvents:UIControlEventTouchUpInside];

return;

}

}

}

}


- (void)keyboardDidHideWeight:(NSNotification *)note {

[[NSNotificationCenter defaultCenter] removeObserver:self];

}


Labels: ,


 
Newer Entries »