Wednesday, August 28, 2013

iOS - KVO programming

declare object:
interface StockData : NSObject {
   NSString * stockName;
   float price;
}
@end
@implementation StockData
@end

Add Observer:
[stockForKVO addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];  

Set Value:
myLabel.text = [stockForKVO valueForKey:@"price"];  

Reset Value, trigger observer method:
[stockForKVO setValue:@"20.0" forKey:@"price"];  


Call observer method:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:@"price"])
    {
        myLabel.text = [stockForKVO valueForKey:@"price"];
    }

}

Remove observer:
- (void)dealloc
{
    [super dealloc];
    [stockForKVO removeObserver:self forKeyPath:@"price"];
    [stockForKVO release];
}

Wednesday, August 14, 2013

iOS- Notes for Predicates Programming Guide

This is my notes for reading Apple Predicates Programming Guide

Reference: http://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Conceptual/Predicates/Articles/pUsing.html


Introduction to Predicates Programming Guide

A predicate is a logical operator that returns a Boolean value (true or false). There are two types of predicate;

comparison predicates, and compound predicates:
A comparison predicate compares two expressions using an operator.

A compound predicate compares the results of evaluating two or more other predicates, or negates
another predicate.


Predicate Classes
Cocoa provides three predicate classes: NSPredicate, and two subclasses of NSPredicate,

NSComparisonPredicate and NSCompoundPredicate.

Predicate expressions in Cocoa are represented by instances of NSExpression.


Creating Predicates
Creating a Predicate Using a Format String

NSPredicate *predicate = [NSPredicate
predicateWithFormat:@"(lastName like[cd] %@) AND (birthday > %@)",
lastNameSearchString, birthdaySearchDate];
(In the example, like[cd] means“case- and diacritic-insensitive like.”)

String Constants, Variables, and Wildcards
String constants must be quoted within the expression—single and double quotes are both acceptable, but must be paired appropriately

NSPredicate *predicate = [NSPredicate
predicateWithFormat:@"lastName like[c] \"S*\""];

You must take automatic quotation into account when using wildcards—you must add wildcards to a variable prior to substitution, as shown in the following example.

NSString *prefix = @"prefix";
NSString *suffix = @"suffix";
NSPredicate *predicate = [NSPredicate
predicateWithFormat:@"SELF like[c] %@",
[[prefix stringByAppendingString:@"*"] stringByAppendingString:suffix]];
BOOL ok = [predicate evaluateWithObject:@"prefixxxxxxsuffix"];


Boolean Values
NSPredicate *newPredicate =
[NSPredicate predicateWithFormat:@"anAttribute == %@", [NSNumber
numberWithBool:aBool]];
NSPredicate *testForTrue =
[NSPredicate predicateWithFormat:@"anAttribute == YES"];

Dynamic Property Names
Because string variables are surrounded by quotation marks when they are substituted into a format string using %@, you cannot use %@ to specify a dynamic property name—as illustrated in the following example.

NSString *attributeName = @"firstName";
NSString *attributeValue = @"Adam";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ like %@",
attributeName, attributeValue];

The predicate format string in this case evaluates to "firstName" like "Adam".

If you want to specify a dynamic property name, you use %K in the format string, as shown in the following fragment.

predicate = [NSPredicate predicateWithFormat:@"%K like %@",
attributeName, attributeValue];

The predicate format string in this case evaluates to firstName like "Adam" (note that there are no
quotation marks around firstName).

Creating Predicates Directly in Code

NSComparisonPredicate and
NSCompoundPredicate provide convenience methods that allow you to easily create compound and
comparison predicates respectively. NSComparisonPredicate provides a number of operators ranging from simple equality tests to custom functions.

The following example shows how to create a predicate to represent (revenue >= 1000000) and (revenue < 100000000). Note that the same left-hand side expression is used for both comparison predicates.

NSExpression *lhs = [NSExpression expressionForKeyPath:@"revenue"];

NSExpression *greaterThanRhs = [NSExpression expressionForConstantValue:[NSNumber
numberWithInt:1000000]];
NSPredicate *greaterThanPredicate = [NSComparisonPredicate
predicateWithLeftExpression:lhs
rightExpression:greaterThanRhs
modifier:NSDirectPredicateModifier
type:NSGreaterThanOrEqualToPredicateOperatorType
options:0];

NSExpression *lessThanRhs = [NSExpression expressionForConstantValue:[NSNumber
numberWithInt:100000000]];
NSPredicate *lessThanPredicate = [NSComparisonPredicate
predicateWithLeftExpression:lhs
rightExpression:lessThanRhs
modifier:NSDirectPredicateModifier
type:NSLessThanPredicateOperatorType
options:0];

NSCompoundPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:
@[greaterThanPredicate, lessThanPredicate]];


Creating Predicates Using Predicate Templates

NSPredicate *predicateTemplate = [NSPredicate
predicateWithFormat:@"lastName like[c] $LAST_NAME"];

To create a valid predicate to evaluate against an object, you use the NSPredicate method
predicateWithSubstitutionVariables: to pass in a dictionary that contains the variables to be
substituted. (Note that the dictionary must contain key-value pairs for all the variables specified in the predicate.)

NSPredicate *predicate = [predicateTemplate predicateWithSubstitutionVariables:
[NSDictionary dictionaryWithObject:@"Turner" forKey:@"LAST_NAME"]];

The new predicate returned by this example is lastName LIKE[c] "Turner

Because the substitution dictionary must contain key-value pairs for all the variables specified in the predicate, if you want to match a null value, you must provide a null value in the dictionary, as illustrated in the following example.

NSPredicate *predicate = [NSPredicate
predicateWithFormat:@"date = $DATE"];
predicate = [predicate predicateWithSubstitutionVariables:
[NSDictionary dictionaryWithObject:[NSNull null] forKey:@"DATE"]];

The predicate formed by this example is date ==

Format String Summary
@"attributeName == %@"
This predicate checks whether the value of the key attributeName isthe same asthe value of the object
%@ that is supplied at runtime as an argument to predicateWithFormat:. Note that %@ can be a
placeholder for any object whose description is valid in the predicate, such as an instance of NSDate,
NSNumber, NSDecimalNumber, or NSString.

@"%K == %@"
This predicate checks whether the value of the key %K is the same as the value of the object %@. The
variables are supplied at runtime as arguments to predicateWithFormat:.

@"%K == '%@'"
This predicate checks whether the value of the key %K is equal to the string literal “%@“ (note the single quotes around %@). The key name %K is supplied at runtime as an argument to predicateWithFormat:.

@"name IN $NAME_LIST"
This is a template for a predicate that checks whether the value of the key name is in the variable
$NAME_LIST (no quotes) that is supplied at runtime using predicateWithSubstitutionVariables:

@"'name' IN $NAME_LIST"
This is a template for a predicate that checks whether the constant value 'name' (note the quotes around
the string) is in the variable $NAME_LIST that is supplied at runtime using
predicateWithSubstitutionVariables:.

@"$name IN $NAME_LIST"
This is a template for a predicate that expects values to be substituted (using
predicateWithSubstitutionVariables:) for both $NAME and $NAME_LIST.

Using Predicates
Evaluating Predicates
To evaluate a predicate, you use the NSPredicate method evaluateWithObject: and pass in the object
against which the predicate will be evaluated. The method returns a Boolean value—in the following example,
the result is YES.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", @[@"Stig",
@"Shaffiq", @"Chris"]];
BOOL result = [predicate evaluateWithObject:@"Shaffiq"];

Using Predicates with Arrays
NSArray and NSMutableArray provide methods to filter array contents. NSArray provides
filteredArrayUsingPredicate: which returns a new array containing objects in the receiver that match
the specified predicate. NSMutableArray provides filterUsingPredicate: which evaluates the receiver’s
content against the specified predicate and leaves only objects that match.

NSMutableArray *array =
[NSMutableArray arrayWithObjects:@"Nick", @"Ben", @"Adam", @"Melissa", nil];
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c]
'a'"];
NSArray *beginWithB = [array filteredArrayUsingPredicate:bPredicate];
// beginWithB contains { @"Adam" }.
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c]
'e'"];
[array filterUsingPredicate:sPredicate];
// array now contains {@"Ben", @"Melissa" }

Using Predicates with Key-Paths
NSString *departmentName = ... ;
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"department.name like %@", departmentName];

If you use a to-many relationship, the construction of a predicate is slightly different. If you want to fetch Departments in which at least one of the employees has the first name "Matthew," for instance, you use an ANY operator as shown in the following example:

NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"ANY employees.firstName like 'Matthew'"];

If you want to find Departments in which at least one of the employees is paid more than a certain amount, you use an ANY operator as shown in the following example:

float salary = ... ;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY employees.salary
> %f", salary];

Null Values
A comparison predicate does not match any value with null except null (nil) or the NSNull null value (that is, ($value == nil) returns YES if $value is nil)

Testing for Null
If you want to match null values, you must include a specific test in addition to other comparisons, as illustrated in the following fragment.

predicate = [NSPredicate predicateWithFormat:@"(firstName == %@) || (firstName =
nil)", firstName];
filteredArray = [array filteredArrayUsingPredicate:predicate];
NSLog(@"filteredArray: %@", filteredArray);
// Output:
// filteredArray: ( { lastName = Turner; }, { birthday = 1972-03-23 20:45:32 -0800;
firstName = Ben; lastName = Ballard; }

By implication, a test for null that matches a null value returns true. In the following code fragment, ok is set to YES for both predicate evaluations.

predicate = [NSPredicate predicateWithFormat:@"firstName = nil"];
BOOL ok = [predicate evaluateWithObject:[NSDictionary dictionary]];
ok = [predicate evaluateWithObject:
[NSDictionary dictionaryWithObject:[NSNull null] forKey:@"firstName"]];

Using Predicates with Core Data
Fetch Requests
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Employee"
inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSNumber *salaryLimit = <#A number representing the limit#>;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"salary > %@",
salaryLimit];
[request setPredicate:predicate];
NSError *error;

NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];

Regular Expressions
NSArray *array = @[@"TATACCATGGGCCATCATCATCATCATCATCATCATCATCATCACAG",
@"CGGGATCCCTATCAAGGCACCTCTTCG", @"CATGCCATGGATACCAACGAGTCCGAAC",
@"CAT", @"CATCATCATGTCT", @"DOG"];
// find strings that contain a repetition of at least 3 'CAT' sequences,
// but not followed by a further 'CA'
NSPredicate *catPredicate =
[NSPredicate predicateWithFormat:@"SELF MATCHES '.*(CAT){3,}(?!CA).*'"];
NSArray *filteredArray = [array filteredArrayUsingPredicate:catPredicate];
// filteredArray contains just 'CATCATCATGTCT'

According to the ICU specification, regular expression meta characters are not valid inside a pattern set. For example, the regular expression \d{9}[\dxX] does not match valid ISBN numbers (any ten digit number, or a string with nine digits and the letter 'X')since the pattern set ([\dxX]) contains a meta character (\d). Instead you could write an OR expression, as shown in the following code sample:

NSArray *isbnTestArray = @[@"123456789X", @"987654321x", @"1234567890", @"12345X",
@"1234567890X"];
NSPredicate *isbnPredicate =
[NSPredicate predicateWithFormat:@"SELF MATCHES '\\\\d{10}|\\\\d{9}[Xx]'"];
NSArray *isbnArray = [isbnTestArray filteredArrayUsingPredicate:isbnPredicate];
// isbnArray contains (123456789X, 987654321x, 1234567890)

Performance
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"( title matches .*mar[1-10] ) OR ( type = 1 )"];
you should write
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"( type = 1 ) OR ( title matches .*mar[1-10] )"];

In the second example, the regular expression is evaluated only if the first clause is false.

Predicate Format String Syntax
Parser Basics

Variables are denoted with a $ (for example $VARIABLE_NAME). ? is not a valid parser token.

%@ is a var arg substitution for an object value—often a string, number, or date.

%K is a var arg substitution for a key path.


When string variables are substituted into a format string using %@ , they are surrounded by quotation marks. If you want to specify a dynamic property name, use %K in the format string, as shown in the following example.

NSString *attributeName = @"firstName";
NSString *attributeValue = @"Adam";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like %@",
attributeName, attributeValue];

The predicate format string in this case evaluates to firstName like "Adam“

Basic Comparisons
Boolean Value Predicates

TRUEPREDICATE
A predicate that always evaluates to TRUE.
FALSEPREDICATE
A predicate that always evaluates to FALSE.

String Comparisons
BEGINSWITH
The left-hand expression begins with the right-hand expression.

CONTAINS
The left-hand expression contains the right-hand expression.

ENDSWITH
The left-hand expression ends with the right-hand expression.

LIKE
The left hand expression equals the right-hand expression: ? and * are allowed as wildcard characters,
where ? matches 1 character and * matches 0 or more characters

MATCHES
The left hand expression equals the right hand expression using a regex-style comparison according to
ICU v3

Aggregate Operations
ANY, SOME

Specifies any of the elements in the following expression. For example ANY children.age < 18.

ALL

Specifies all of the elements in the following expression. For example ALL children.age < 18.

NONE
Specifies none of the elements in the following expression. For example, NONE children.age < 18.

This is logically equivalent to NOT (ANY ...).

IN
Equivalent to an SQL IN operation, the left-hand side must appear in the collection specified by the
right-hand side.
For example, name IN { 'Ben', 'Melissa', 'Nick' }. The collection may be an array, a set, or a
dictionary—in the case of a dictionary, its values are used.
In Objective-C, you could create a IN predicate as shown in the following example:

NSPredicate *inPredicate =
[NSPredicate predicateWithFormat: @"attribute IN %@", aCollection];

where aCollection may be an instance of NSArray, NSSet, NSDictionary, or of any of the
corresponding mutable classes.

Reserved Words

The following words are reserved:
AND, OR, IN, NOT, ALL, ANY, SOME, NONE, LIKE, CASEINSENSITIVE, CI, MATCHES, CONTAINS, BEGINSWITH,
ENDSWITH, BETWEEN, NULL, NIL, SELF, TRUE, YES, FALSE, NO, FIRST, LAST, SIZE, ANYKEY, SUBQUERY, CAST,

TRUEPREDICATE, FALSEPREDICATE



Tuesday, August 6, 2013

iOS- Create push notification private key by shell script

To use the push notification, you need to create a  p12 private key file to your server side. I would like to create a shell script for it. Then you can reuse it for some time.

First of all, you need to three source file :1.certSigningRequest, 2.p12(private key for the certificate), 3.cer(provision profile)

for example, using .Net to send push notification, you need to create a p12 file, you need to type 3 lines of command, which is

then you need to type the followinig command as below:

openssl x509 -in 3.cer -inform der -out PushCert.pem

openssl pkcs12 -nocerts -out PushKey.pem -in 2.p12


openssl pkcs12 -export -in PushCert.pem -inkey PushKey.pem -certfile 1.certSigningRequest -name "apn_production_identity" -out apn_production_identity.p12

Step one:
Open your terminal, type vim my_script

Step two:
input the following words:

#!/bin/bash
# Create push p12 file

openssl x509 -in 3.cer -inform der -out PushCert.pem

openssl pkcs12 -nocerts -out PushKey.pem -in 2.p12

openssl pkcs12 -export -in PushCert.pem -inkey PushKey.pem -certfile 1.certSigningRequest -name "apn_production_identity" -out apn_production_identity.p12



Step three:
save the file and put the source files and my_script in the same folder

Step four:
Open terminal, cd to the folder, run
bash my_script

After enter the password to verify, then you will get the p12 file, which is apn_production_identity.p12