Archive for the ‘Apple’ Category

01
feb

Suppose that we have a ViewController.h and .m like this:

1
2
3
4
5
// ViewController.h
#import UIKit/UIKit.h

@interface ViewController : UIViewController
@end
1
2
3
4
5
6
7
8
9
10
11
12
// ViewController.m
#import "ViewController.h"
#import "SetValue.h"

@implementation ViewController
- (void)viewDidLoad
{
  [super viewDidLoad];

  [SetValue SetTheValue:@"a string"];
}
@end

And a class called SetValue, with two methods.

1
2
3
4
5
6
7
8
9
// SetValue.h
#import Foundation/Foundation.h

@interface SetValue : NSObject { }

+ (void) SetTheValue:(id)Obj;
- (void) MySelector:(id)Obj;

@end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// SetValue.m
#import "SetValue.h"

@implementation SetValue

+ (void) SetTheValue:(id)Obj
{
  [self performSelectorOnMainThread:@selector(MySelector:)
                withObject:Obj
                waitUntilDone:NO];
}

- (void) MySelector:(id)Obj
{
  NSLog(@"Data: %@", [Obj description]);
}

@end

What is the value printed by the NSLog?

enjoy.

Ref: albertopasca.it


FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

01
feb

NSString and retainCount memo:

1
2
3
4
5
6
7
8
    NSString *A = [[NSString alloc] init];
    NSLog(@"_A_RC: %i", [A retainCount]);

    NSString *B = [[NSString alloc] initWithFormat:@"AAA"];
    NSLog(@"_B_RC: %i", [B retainCount]);

    NSString *C = [[NSString alloc] initWithString:@"AAA"];
    NSLog(@"_C_RC: %i", [C retainCount]);
1
2
3
...Test[3530:15203] _A_RC: -1  (ios < 5 = 2147483647)
...Test[3530:15203] _B_RC: 1
...Test[3530:15203] _C_RC: -1  (ios < 5 = 2147483647)

Because your string is not in the heap, but is a constant. A NSString made from a constant NSString is identical to the original NSString.

UINT_MAX (2147483647) -> http://it.wikipedia.org/wiki/2147483647

Ref: albertopasca.it


FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , ,

21
dic

Reading Info.plist:

1
2
  NSBundle*  mainBundle = [NSBundle mainBundle];
  NSLog(@"%@", [mainBundle objectForInfoDictionaryKey:@"UIBackgroundModes"]);

Writing Info.plist

You can’t.
App bundles are read-only because they are signed, changing their content would break the signing and the app would be considered to be tampered with and not run.

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

16
dic

Here a unix command line script to count code lines for your project (or something else!).

In this example it counts lines in an Objective-C iOS Application (.h or .m files).

1
2
3
4
$
$find . \( -name '*.h' -o -name '*.m' \) -print -exec cat {} \; | wc -l
  25812
$


Explanation:

find . \( -name ‘*.h’ -o -name ‘*.m’ \) -print

- list all files endings with .H or .M recursively from current folder (.).

-exec cat {} \;

- while it finds files, exec a cat on current file

wc -l

- count lines of current file and sum it to total.

25812 lines of code! Sounds good!

enjoy!

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , ,

04
ott

Getting the Length of a String

The length of the string in a string object can be obtained by accessing the length method of the string object:

1
2
3
NSString *string1 = @"This string is Immutable";
int len = [string1 length];
NSLog (@"String length is %i", len);

Searching for a Substring

A common requirement when working with strings is to identify whether a particular sequence of characters appears within a string. This can be achieved using the rangeOfString method. This method returns a structure of type NSRange. The NSRange structure contains a location value providing the index into the string of the matched substring and a length value indicating the length of the match.

1
2
3
4
5
NSString *string1 = @"The quick brown fox jumped";
NSRange match;
match = [string1 rangeOfString: @"brown fox"];
NSLog (@"match found at index %i", match.location);
NSLog (@"match length = %i", match.length);

The NSLog call will display the location and length of the match. Note that the location is an index into the string where the match started and that the index considers the first position in a string to be 0 and not 1. As such, the location in our example will be 10 and the length will be 9.

In the event that no match is found, the rangeOfString method will set the location member of the NSRange structure to NSNotFound. For example:

1
2
3
4
5
6
7
NSString *string1 = @"The quick brown fox jumped";
NSRange match;
match = [string1 rangeOfString: @"brown dog"];
if (match.location == NSNotFound)
  NSLog (@"Match not found");
else
  NSLog (@"match found at index %i", match.location);

Replacing Parts of a String

Sections of a mutable string may be replaced by other character sequences using the replaceCharactersInRange method. This method directly modifies the string object on which the method is called so only works on mutable string objects.

This method requires two arguments. The first argument is an NSRange structure consisting of the location of the first character and the total number of characters to be replaced. The second argument is the replacement string. An NSRange structure can be created by calling NSMakeRange and passing though the location and length values as arguments. For example, to replace the word “fox” with “squirrel” in our sample mutable string object we would write the following Objective-C code:

1
2
3
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 replaceCharactersInRange: NSMakeRange(16, 3) withString: @"squirrel"];
NSLog (@"string1 = %@", string1);

As you may have noted from the above example, the replacement string does not have to be the same length as the range being replaced. The string object and replacement method will resize the string automatically.

String Search and Replace

Previously we have covered how to perform a search in a string and how to replace a subsection of a string using the rangeOfString and replaceCharactersInRange methods respectively. The fact that both of these methods use the NSRange structure enables us to combine the two methods to perform a search and replace. In the following example, we use rangeOfString to provide us with an NSRange structure for the substring to be replace and then pass this through to replaceCharactersInRange to perform the replacement:

1
2
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 replaceCharactersInRange: [string1 rangeOfString: @"brown fox"] withString: @"black dog"];

When executed, string1 will contain the string “The quick black dog jumped”.

Deleting Sections of a String

Similar techniques to those described above can be used to delete a subsection of a string using the deleteCharactersInRange method. As with the preceding examples, this method accepts an NSRange structure as an argument and can be combined with the rangeOfString method to perform a search and delete:

1
2
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 deleteCharactersInRange: [string1 rangeOfString: @"jumped"]];

Extracting a Subsection of a String

A subsection of a string can be extracted using the substringWithRange method. The range is specified using an NSRange structure and the extracted substring is returned in the form of an NSString object:

1
2
3
4
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
NSString *string2;
string2 = [string1 substringWithRange: NSMakeRange (4, 5)];
NSLog (@"string2 = %@", string2);

When executed, the above code will output the substring assigned to string2 (“quick”).

Alternatively, a substring may be extracted from a given index until the end of the string using the subStringFromIndex method. For example:

1
2
3
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
NSString *string2;
string2 = [string1 substringFromIndex: 4];

Similarly, the subStringToIndex may be used to extract a substring from the beginning of the source string up until a specified character index into the string.

Inserting Text into a String

The insertString method inserts a substring into a string object and takes as arguments the NSString object from which the new string is to inserted and the index location into the target string where the insertion is to be performed:

1
2
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 insertString: @"agile, " atIndex: 4];

Appending Text to the End of a String

Text can be appended to the end of an existing string object using the appendString method. This method directly modifies the string object on which the method is called and as such is only available for mutable string objects.

1
2
3
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 appendString: @" over the lazy dog"];
NSLog (@"string1 = %@", string1);

Comparing Strings

String objects cannot be compared using the equality (==) operator. The reason for this is that any attempt to perform a comparison this way will simply compare whether the two string objects are located at the same memory location. Let’s take a look at this via an example:

1
2
3
4
5
6
NSString *string1 = @"My String";
NSString *string2 = @"My String";
if (string1 == string2)
  NSLog (@"Strings match");
else
  NSLog (@"Strings do not match");

In the above code excerpt, string1 and string2 are pointers to two different string objects both of which contain the same character strings. If we compare them using the equality operator, however, we will get a “Strings do not match” result. This is because the if (string1 == string2) test is asking whether the pointers point to the same memory location. Since string1 and string2 point to entirely different objects the answer, obviously, is no.

We can now take this a step further and change the code so that both string1 and string2 point to the same string object:

1
2
3
4
5
6
7
NSString *string1 = @"My String";
NSString *string2;
string2 = string1;
if (string1 == string2)
  NSLog (@"Strings match");
else
  NSLog (@"Strings do not match");

Now when we run the code, we get a “Strings match” result because both variables are pointing to the same object in memory.

To truly compare the actual strings contained within two string objects we must use the isEqualToString method:

1
2
3
4
5
6
NSString *string1 = @"My String";
NSString *string2 = @"My String 2";
if ([string1 isEqualToString: string2])
  NSLog (@"Strings match");
else
  NSLog (@"Strings do not match");

Another option is to use the compare method (to perform a case sensitive comparison) or the caseInsenstiveCompare NSString methods. These are more advanced comparison methods that can be useful when sorting strings into order.

Checking for String Prefixes and Suffixes

A string object can be tested to identify whether the string begins or ends with a particular sequence of characters (otherwise known as prefixes and suffixes). This is achieved using the hasPrefix and hasSuffix methods respectively, both of which return boolean values based on whether a match is found or not.

1
2
3
4
5
6
7
8
9
NSString *string1 = @"The quick brown fox jumped";
BOOL result;
result = [string1 hasPrefix: @"The"];
if (result)
  NSLog (@"String begins with The");

result = [string1 hasSuffix: @"dog"];
if (result)
NSLog (@"String ends with dog");

Converting to Upper or Lower Case

The Foundation NSString classes provide a variety of methods for modifying different aspects of case within a string. Note that each of these methods returns a new string object reflecting the change, leaving the original string object unchanged.

1
capitalizedString

Returns a copy of the specified string with the first letter of each word capitalized and all other characters in lower case:

1
2
3
NSString *string1 = @"The quicK brOwn fox jumpeD";
NSString *string2;
string2 = [string1 capitalizedString];

The above code will return a string object containing the string “The Quick Brown Fox Jumped” and assign it to the string2 variable. The string object referenced by string1 remains unmodified.

1
lowercaseString

Returns a copy of the specified string with all characters in lower case:

1
2
3
NSString *string1 = @"The quicK brOwn fox jumpeD";
NSString *string2;
string2 = [string1 lowercaseString];

The above code will return a string object containing the string “the quick brown fox jumped” and assign it to the string2 variable. The string object referenced by string1 remains unmodified.

1
uppercaseString

Returns a copy of the specified string with all characters in upper case:

1
2
3
NSString *string1 = @"The quicK brOwn fox jumpeD";
NSString *string2;
string2 = [string1 uppercaseString];

The above code will return a string object containing the string “THE QUICK BROWN FOX JUMPED” and assign it to the string2 variable. The string object referenced by string1 remains unmodified.

Converting Strings to Numbers

String objects can be converted to a variety of number types:

Convert String to int

1
2
3
NSString *string1 = @"10";
int myInt = [string1 intValue];
NSLog (@"%i", myInt);

Convert String to double

1
2
3
NSString *string1 = @"10.1092";
double myDouble = [string1 doubleValue];
NSLog (@"%f", myDouble);


Convert String to float

1
2
3
NSString *string1 = @"10.1092";
float myFloat = [string1 floatValue];
NSLog (@"%f", myFloat);

Convert String to NSInteger

1
2
3
NSString *string1 = @"10";
NSInteger myInteger = [string1 integerValue];
NSLog (@"%li", myInteger);

Converting a String Object to ASCII

The string contained within a string object can be extracted and converted to an ASCII C style character string using the UTF8String method. For example:

1
2
3
NSString *string1 = @"The quick browen fox";
const char *utfString = [string1 UTF8String];
printf ("Converted string = %s\n", utfString);

Rif: http://www.techotopia.com
Rif: albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , , , , , , , , , , , , , , ,

24
set

Do you want use google speech api to recognize text from a dictate?

If you want to add in your “test” project, (test project because it’s not a public API), you need to read Chrome Browser source code.

Here chromium url: src.chromium.org/viewvc/chrome/trunk/src/content/browser/speech

Chrome records audio chunks, accepts only a FLAC file, an open source audio codec (free lossless audio codec) file with a sample rate of 16000.0!

After upload to server:

https://www.google.com/speech-api/v1/recognize

and server responds with a json like this:

1
2
3
4
5
6
7
8
9
10
11
12
{
    "status": 0,
    "id": "f3847b5dcu4d657f6667f3pk4sc0a8ca-2",
    "hypotheses": [
    {
        "utterance": "it works",
        "confidence": 0.8012238
    },
    {
        "utterance": "it works"
    }]
}

Now, using ASIFormDataRequest we can send in POST a file to google url waiting for JSON.
Objective-c code:

1
2
3
4
5
6
7
8
9
10
11
12
13
- (void) SpeechFromGooglezzz {
  NSURL *url = [NSURL URLWithString:@"https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=en-US"];

  ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
  NSString *filePath = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"tmpAudio.flac"];

  NSData *myData = [NSData dataWithContentsOfFile:filePath];
  [request addPostValue:myData forKey:@"Content"];
  [request addPostValue:@"audio/x-flac; rate=16000" forKey:@"Content-Type"];
  [request startSynchronous];

  NSLog(@"req: %@", [request responseString]);
}

But now is there a big problem… objective-c and iphone don’t recognize FLAC files, you need an intermediate passage to send the correct audio file.

Set up your server with FFMPEG (an audio/video converting/editing tool) and prepare a PHP/JSP/etc. that accept in post an audio file, call a PHP EXEC and launch ffmpeg with flac codec.
Then upload from server to google and return response!

Here code to record and listen audio file from iPhone. Create two buttons and copy/paste code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- (IBAction)StartRec:(id)sender {  
  NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                            [NSNumber numberWithFloat: 16000.0],                 AVSampleRateKey,
                            [NSNumber numberWithInt: kAudioFormatMPEGLayer3],    AVFormatIDKey,
                            [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
                            [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
                            nil];
 
  NSError *error;
  NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"tmpAudio.mp3"]];
  recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
 
  if (recorder) {
    [recorder prepareToRecord];
    [recorder record];
  }
  else NSLog(@"%@", [error description]);
}
1
2
3
4
5
6
7
8
9
10
11
12
- (IBAction)PlayAudio:(id)sender {
 NSString *path = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"tmpAudio.mp3"];
 
 SystemSoundID soundID;  
 NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
 AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
 AudioServicesPlaySystemSound(soundID);
}

- (IBAction)StopRec:(id)sender {
  if (recorder) [recorder stop];
}

That’s all, enjoy!

…and remember that speech function of google it’s a private API. You can’t use in a commercial app!

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , , ,

02
ago

Cutaway App for iPhone/iPod/iPad 3.2+. [cutaway.it]

CutAway - CutAway SRL
New release 1.0.3 – bug fix.


Cutaway app mobile iphone ipad

CutAway - CutAway SRL

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , ,

14
mar

Today a little tutorial to find a word in a big ordered text file using binary search in objective-c.





What is binary search? (Wikipedia -> http://en.wikipedia.org/wiki/Binary_search_algorithm)

A binary search or half-interval search algorithm locates the position of an item in a sorted array. Binary search works by comparing an input value to the middle element of the array. The comparison determines whether the element equals the input, less than the input or greater. When the element being compared to equals the input the search stops and typically returns the position of the element. If the element is not equal to the input then a comparison is made to determine whether the input is less than or greater than the element. Depending on which it is the algorithm then starts over but only searching the top or bottom subset of the array’s elements. If the input is not located within the array the algorithm will usually output a unique value indicating this. Binary search algorithms typically halve the number of items to check with each successive iteration, thus locating the given item (or determining its absence) in logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.


How to do it in Objective-C language?

First of all you need a text file containing a word on each line like this snippet:

[...]
vuotato
vuotava
vuotavamo
vuotavano
vuotavate
[...]

You need to read all file and save each line in an array.





Snippet in Objecitve-C using C stdlib

1
#include <stdlib .h>
1
2
3
4
5
6
7
8
9
10
  char buffer[512];
  NSMutableArray *mySortedArray = [NSMutableArray array];
  int charsRead = 512;
  do {
    if(fscanf(file, "%s\n", buffer, &charsRead) == 1)
      [mySortedArray addObject:[NSString stringWithFormat:@"%s", buffer]];
    else
      break;
  } while(charsRead == 512);
  fclose(file);

Once you’ve getted all lines, you can use

1
CFArrayBSearchValues

to make a binary search in your array.
Very easy yo use.

You don’t understand this snippet?
Here the full version of binary search in objective-c.
Continue reading “[Objective-C] Fast String Binary Search” »

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , , , ,

21
feb

From your terminal:

1
alberto$ defaults write com.apple.Xcode NSRecentDocumentsLimit 0

done.

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , ,

Switch to our mobile site