Archive for the ‘Objective-C’ 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.

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

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

Great idea!
Follow this link: http://appsumo.com/~_z6T and you can win a paid account for Github!
You need only respond to a simple question! :)

Do you know GitHub.com?

git·hub /’ɡɪtˌhʌb/
GitHub is the best way to collaborate with others. Fork, send pull requests and manage all your public and private git repositories.


Github Free Account

Click here http://appsumo.com/~_z6T and Win!

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

, , , , , , , , , , ,

06
set

Here a method that consider earth curve.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- (float) CalculateDistanceFromCurrent:(CLLocationCoordinate2D)currentCoords andDestination:(CLLocationCoordinate2D)destCoords {
 
  const float a = 6378.137;
  const float e = (1/298.257);
  const float pi = 3.141593;
 
  float x1 = currentCoords.latitude;
  float x2 = destCoords.latitude;
  float y1 = currentCoords.longitude;
  float y2 = destCoords.longitude;
 
  float distance =
  acos ( sin ( y1 * pi / 180 ) * sin ( y2 * pi / 180 ) +
        cos ( y1 * pi / 180 ) * cos ( y2 * pi / 180 ) *
        cos ( ( x2 - x1 ) * pi / 180 ) ) * a * sqrt ( 1 - e * e ) /
  ( 1 - e * e * sin ( ( y1 + y2 ) * pi / 360 ) * sin ( ( y1 + y2 ) * pi / 360 ) );
 
  return distance;
}

It returns kilometers.

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

, , , ,

07
mag

Hi all!!
Today i show how is possible to connect iPhone to Arduino without any Wifi or Ethernet shields!

Here the app that controls 4 leds (green yellow, red and orange), a DC motor with a fan, a piezo speacker and the room temperature with LM32 sensor!


Arduino iphone control


What you need?
Arduino with anything you want
iPhone / iPad / iPod
– A website to host php pages
– An internet connection on pc (Win + Mac)

What you need to know?
– A little bit of electronics
C language
C# language
PHP language
Objective-C language

Good.
In PHP make a stupid page that get in $_REQUEST a command and store it to a file on server!
Three lines of code…

In C# make a web listener that call php page and checks the output. If any condition are verified, send to COM9 the value that you want to get from arduino.

In C from Arduino, in the Loop() read Serial value. If the value respond to your configuration, call LigthUpLed(green) for example!

In Objective-C make an iPhone App with a stupid layout that call in GET your PHP page and send a command!

To make everithink work, run your C# listener app on Windows and from your iPhone send get call to web server!

Now, your nerd app will control arduino!!!

In this example app that i made, i control HIGH or LOW for Four LEDs, a DC Motor, a Piezo Speacker and a Temperature Sensor.

I used resistors, 4 leds, LM32, DC Motor, TIP120, diode, wires, beer.




Here a screenshot (click to enlarge):


Arduino iphone control

Here a video:



Rif: albertopasca.it

enjoy!

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , ,

07
apr

Hi all,
a promemoria to MERGE Device + Simulator libraries in a “fat” lib with XCODE.

Usage:

1. Create a static lib project
2. Select the Target
3. right-click and “Add … New Build Phase … New Run Script Build Phase”
4. Copy/paste the script below into the box

After that, customize script as you want!

In your BUILD folder you can see Release-Universal folder that contains merged libs with headers file!




Ref: albertopasca.it

Here the code:

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
### EXECUTED ONLY WITH SIMULATOR->RELEASE->MyTarget

#!/bin/sh

### CONFIG VARS
MY_TARGET="MyTarget"
IS_VALID="FALSE"
SDK_VERSION=$(echo ${SDK_NAME} | grep -o '.\{3\}$')
ALREADYINVOKED="false"
UNIVERSAL_NAME="Release-universal"
BUILD_DEV_PATH=${BUILD_DIR}/${UNIVERSAL_NAME}/tmp-dev/
BUILD_SIM_PATH=${BUILD_DIR}/${UNIVERSAL_NAME}/tmp-sim/

### CONF CHECK
CheckConfig() {
 # YOUR COMPILE RULES
 if [ ${CONFIGURATION} == "Release" ] &&
    [ ${ACTION} == "build" ] &&
    [ ${TARGET_NAME} == ${MY_TARGET} ] &&
    [ ${PLATFORM_NAME} == "iphonesimulator" ]
 then
  IS_VALID="TRUE"
 fi
}

### MKDIRS
CreateFolders() {
 mkdir -p "${SYMROOT}/${UNIVERSAL_NAME}/"
 mkdir -p  ${BUILD_DEV_PATH}
 mkdir -p  ${BUILD_SIM_PATH}
 mkdir -p "${SYMROOT}/${UNIVERSAL_NAME}/include"
}

### MULTIPLE BUILDS
BuildLibs() {
 # BUILD DEVICE
 xcodebuild -configuration "Release" -target "PGLib" -sdk "iphoneos4.3" build RUN_CLANG_STATIC_ANALYZER=NO BUILD_DIR="${BUILD_DEV_PATH}" BUILD_ROOT="${BUILD_DEV_PATH}"
 # BUILD SIMULATOR
 xcodebuild -configuration "Release" -target "PGLib_Simulator" -sdk "iphonesimulator4.3" build RUN_CLANG_STATIC_ANALYZER=NO BUILD_DIR="${BUILD_SIM_PATH}" BUILD_ROOT="${BUILD_SIM_PATH}"
}

### MERGE LIBS
FatLibs() {
 LIB_DEV="${BUILD_DEV_PATH}/Release-iphoneos/libPGLib-DEV.a"
 LIB_SIM="${BUILD_SIM_PATH}/Release-iphonesimulator/libPGLib-SIM.a"
 LIB_UNI="${SYMROOT}/${UNIVERSAL_NAME}/libPGLib.a"
 HEADERS="${BUILD_DEV_PATH}/Release-iphoneos/usr/local/include/"

 cp "${HEADERS}"/* "${SYMROOT}/${UNIVERSAL_NAME}/include"

 lipo -create "${LIB_DEV}" "${LIB_SIM}" -output "${LIB_UNI}"
}

### CLEAN WORKING DATA
ClearTemporary() {
 rm -rf "${BUILD_DEV_PATH}"
 rm -rf "${BUILD_SIM_PATH}"
}

#
### MAIN
#
if [ "true" != ${ALREADYINVOKED:-false} ]; then  # SKIP APPLE RECURSION
 CheckConfig
 ALREADYINVOKED="true"

 if [ ${IS_VALID} == "TRUE" ]; then  # DO WORK
  CreateFolders
  BuildLibs
  FatLibs
  ClearTemporary

  echo "Custom script on RELEASE/SIMULATOR/${MY_TARGET} executed!";
 else
  echo "Custom script SKIPPED execution!";
 fi
fi

enjoy coding!!!






Ref: albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , ,

Switch to our mobile site