Friday, May 31, 2013

Matt Galloway: Singletons in Objective-C

Innen:

Background

Singleton classes are an important concept to understand because they exhibit an extremely useful design pattern. This idea is used throughout the iPhone SDK, for example, UIApplication has a method called sharedApplication which when called from anywhere will return the UIApplication instance which relates to the currently running application.

How to implement

You can implement a singleton class in Objective-C using the following code:

MyManager.h
1
2
3
4
5
6
7
8
9
10
11
#import 

@interface MyManager : NSObject {
    NSString *someProperty;
}

@property (nonatomic, retain) NSString *someProperty;

+ (id)sharedManager;

@end
MyManager.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#import "MyManager.h"

@implementation MyManager

@synthesize someProperty;

#pragma mark Singleton Methods

+ (id)sharedManager {
    static MyManager *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[self alloc] init];
    });
    return sharedMyManager;
}

- (id)init {
  if (self = [super init]) {
      someProperty = [[NSString alloc] initWithString:@"Default Property Value"];
  }
  return self;
}

- (void)dealloc {
  // Should never be called, but just here for clarity really.
}

@end

What this does is it defines a static variable (but only global to this translation unit)) called sharedMyManager which is then initialised once and only once in sharedManager. The way we ensure that it’s only created once is by using the dispatch_once method from Grand Central Dispatch (GCD). This is thread safe and handled entirely by the OS for you so that you don’t have to worry about it at all.

However, if you would rather not use GCD then you should use the following code for sharedManager:

Non-GCD based code
1
2
3
4
5
6
7
+ (id)sharedManager {
    @synchronized(self) {
        if (sharedMyManager == nil)
            sharedMyManager = [[self alloc] init];
    }
    return sharedMyManager;
}

Then you can reference the singleton from anywhere by calling the following function:
MyManager *sharedManager = [MyManager sharedManager];

I’ve used this extensively throughout my code for things such as creating a singleton to handle CoreLocation or CoreData functions.

Thursday, May 16, 2013

UIView kozepre

Ha azt akarjuk hogy az ujjonnan felhelyezett View kozepen maradjon device forgatas utan is akkor:
[myView setAutoresizingMask: UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin];

Thursday, April 25, 2013

Opcionalis delegate method

Egyreszt a @protocol-ban a method kapja meg az @optional direktivat:

@protocol MyProtocol
    @optional
    -(void)optionalProtocolMethod:(id)anObject;
@end

masreszt mivel ez onmagaban csak arra jo, hogy compiler ne adjon warningot meg a method meghivasa elott azt is meg kell nezni, hogy a delegate implementalja-e ezt a method-ot:

if ([delegate respondsToSelector:@selector(myOptionalMethod)]) {
    [delegate myOptionalMethod];
}
A protocol az NSObject-bol kell szarmazzon, mert annak a resze a respondsToSelector

Thursday, April 18, 2013

UIColor

Eleg furan mukodik, ha egy control RGB szinet be akarjuk allitani. a colorWithHue:saturation:brightness:alpha:-nal nem a sima RGB ertekeket kell megadni, hanem egy 0.0 es 1.0 koze eso float-ot, amit ugy kapunk meg, ha az alltalunk ismert RGB ertekeket elosztjuk 255-tel. Tehat peldaul a Red amit kaputunk 50, akkor itt 0.196-ot (50/255) kell megadnunk.

Ha egy UIColor-bol pedig ki szeretnenk nyerni az ertkeket arra a getRed:green:blue:alpha: methodot hasznalhatjuk valahogy igy:

UIColor *color = //get the color to log
CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0;
[color getRed:&red green:&green blue:&blue alpha:&alpha];
NSLog(@"mycolor red:%f green:%f blue:%f alpha:%f", red, green, blue, alpha);

Persze ha nem RGB hanem HSB akkor arra ott van a colorWithHue:saturation:brightness:alpha: es a 
getHue:saturation:brightness:alpha:

Monday, April 8, 2013

Email kuldese app-bol

MFMailComposeViewController-el egyszeruen:


- (void) sendEmail {
    if (![MFMailComposeViewController canSendMail]) {
        HBAlert(@"Can't send email", @"Sorry, your device is not able to send email");
        return;
    }
    MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
    [mailer setMailComposeDelegate:self];
    NSString *subject = @"Whatever subject;
    [mailer setSubject:subject];
    NSString *body = @"This is a test email from my app.";
    [mailer setMessageBody:body isHTML:NO];
    [mailer setModalPresentationStyle:UIModalPresentationFormSheet];
    [self presentViewController:mailer animated:YES completion:nil];
}


- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    switch (result) {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved as draft");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail is sent");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Sending mail failed");
            break;
        default:
            break;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

Friday, April 5, 2013

DigitalColor Meter

Ha mac os-en kell egy keppont szinet megallapitani, akkor DigitalColor Meter.

Thursday, April 4, 2013

Handling Popover Controllers During Orientation Changes

Van egy azonos cimu bejegyzes az Apple-nel ami szerint:

When showing a popover controller, there are times when you will need to handle how the popover controller appears after a change in device orientation.

Situations when handling is required:

If the popover controller is presented from a target rectangle using the –presentPopoverFromRect:inView:permittedArrowDirections:animated: method of UIPopoverController.
If the popover controller is presented from a bar button item that is removed after the rotation has finished.

es ilyenkor a megoldas, ha ujra meghivjuk a presentPopoverFromRect:inView:permittedArrowDirections:animated: method-ot a didRotateFromInterfaceOrientation: eventben, csak azt nem teszik hozza, hogy elotte azert erdemes megnezni, hogy egyaltalan latszott-e a Popover Controller. Szoval helyesen igy nez ki:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
if ([myickerPopover isPopoverVisible]) {
[[self myPickerPopover] presentPopoverFromRect:
[[self myButton] frame] 
inView:[self view] 
permittedArrowDirections: UIPopoverArrowDirectionAny animated:YES];
}
}

Felteve, hogy a myPickerPopover es a myButton elerheto property.

dequeueReusableCellWithIdentifier:forIndexPath:

iOS 6-ban jelent meg a regi dequeueReusableCellWithIdentifier: mellett es ahogy a doksiban is kiemelik
Important: You must register a class or nib file using the registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier: method before calling this method.

Azaz vagy marad a regi modszer ami akar 2-es iOS-en is mukodik:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
return cell;
}


Vagy ha minimum 6-oson hasznaljuk akkor:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    return cell;
}

de ilyenkor fontos, hogy a viewDidLoad-ba betegyuk ezt:
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];




Friday, March 22, 2013

iOS app inditasa URL-lel

Be lehet regisztralni a sajat app-unkhoz URL-eket amikkel meg tudjuk nyitni az appot:
Target/Info/URL Types vagy Supporting Files/app-info.plist
Az identifiert (reverse domain name javasolt com.company.app - bar ez nem tul erdekes) es az URL Schema-t kell kitolteni.

Az app delegate-ben a application:openURL:sourceApplication:annotation method-ban lehet feldolgozni.

Tuesday, March 19, 2013

UISpitViewController-nel portrait modban a szoveges UIBarButtonItem kicserelese egy kepre

- (void)splitViewController:(UISplitViewController *)splitController willHideViewController:(UIViewController *)viewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)popoverController {

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *customImage = [UIImage imageNamed:@"MyImage.png"];
    [button setBackgroundImage:customImage forState:UIControlStateNormal];
    [button setFrame:CGRectMake(0.0, 0.0, customImage.size.width, customImage.size.height)];
    [button addTarget:[barButtonItem target] action:[barButtonItem action] forControlEvents:UIControlEventTouchUpInside];
    [barButtonItem setCustomView:button];

    [self.navigationItem setLeftBarButtonItem:barButtonItem animated:YES];
    self.masterPopoverController = popoverController;
}

Monday, October 8, 2012

Smart App Banners

Ha azt akarjuk, hogy a mobile Safari egy oldal megnyitasanal automatikusan felkinalja egy app letolteset vagy inidtasat, akkor Smart App Banner-t kell hasznalni valahogy igy:

<meta name="apple-itunes-app" content="app-id=311507490"/>

innen: http://david-smith.org/blog/2012/09/20/implementing-smart-app-banners/

Thursday, March 8, 2012

#include/#import/@import

Az #import jobb, mert itt csak egyszer kerul be az improtalt resz es igy elkeruljuk a rekurziv #include-okat akkor is, ha az importalt file-ban nicsen rendesen megadva az include guard.

Jeremy W Sherman szerint az @import jobb lesz barmelyiknel.

Tuesday, March 6, 2012

keychain

Buzz Andersen: Simple iPhone Keychain Code
3 egyszeru method van benne es mukodik simulator-ban is meg device-on is:


+ (NSString *) getPasswordForUsername: (NSString *) username andServiceName: (NSString *) serviceName error: (NSError **) error;

+ (BOOL) storeUsername: (NSString *) username andPassword: (NSString *) password forServiceName: (NSString *) serviceName updateExisting: (BOOL) updateExisting error: (NSError **) error;

+ (BOOL) deleteItemForUsername: (NSString *) username andServiceName: (NSString *) serviceName error: (NSError **) error;


code pedig itt van.
Egyebkent pedig: Keychain Services Programming Guide

+++++++++++
Itt pedig Chris Lowe peldaja ARC eseten.

Monday, March 5, 2012

screencapture


ScreenFlow - $99
SnapzProX - $66
iShowU - $20
SimFinger - free
PhoneFinger - free

Wednesday, February 29, 2012

Felix Schulze: Tutorial: iPhone App with compiled OpenSSL 1.0.0a Library

Itt van.

Ron Gutierrez: Accepting Un-Trusted Certificates Using The IOS Simulator

Itt van.

SubView-k kilogolasa


-(void) printAllChildrenOfView:(UIView*) view depth:(int) d {
    //Tabs are just for formatting
    NSString *tabs = @"";
    for (int i = 0; i < d; i++)
    {
        tabs = [tabs stringByAppendingFormat:@"\t"];
    }
    
    NSLog(@"%@%@", tabs, view);
    
    d++; //Increment the depth
    for (UIView *child in view.subviews)
    {
        [self printAllChildrenOfView:child depth:d];
    }
}

Thursday, February 9, 2012

Wednesday, February 1, 2012

Keyboard eltuntetes UITextField-nel

2 dolgot kell megenni:
- UITextField delagate-jet ra kell allitani a File's Owner-re
-textFieldShoudReturn(UITextFiled *)textField-ben meg kell hivni a textField-en a resignFirstResponder-t valahogy igy:

-(BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    [uploadsURLTextField resignFirstResponder];
    return YES;
}

Wednesday, November 30, 2011

Categories (By Scott Stevenson)

innen


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.

For example, if I wanted to add a method to NSString to determine if the contents is a URL, it would look like this:
 
#import @interface NSString (Utilities) - (BOOL) isURL; @end
This is very similar to a class declaration. The differences are that there is no super class listed, and there's a name for the category in parenthesis. The name can be whatever you want, though it should communicate what the methods inside do.

Here's the implementation. Keep in mind this is not a good implementation of URL detection. We're just trying to get the concept of categories across:
 
#import "NSString-Utilities.h" @implementation NSString (Utilities) - (BOOL) isURL { if ( [self hasPrefix:@"http://"] ) return YES; else return NO; } @end
Now you can use this method on any NSString. The following code will print "string1 is a URL" in the console:
 
NSString* string1 = @"http://pixar.com/"; NSString* string2 = @"Pixar"; if ( [string1 isURL] ) NSLog (@"string1 is a URL"); if ( [string2 isURL] ) NSLog (@"string2 is a URL");
Unlike subclasses, categories can't add instance variables. You can, however, use categories to override existing methods in classes, but you should do so very carefully.

Remember, when you make changes to a class using a category, it affects all instances of that class throughout the application.