Free account for ios deploy real device to test

  • Requires free Apple Developer account, at a minimum. Free account provisioning expires every 7 days, requiring reloading/rebuilding, but you will not lose any data.

    Paid Apple Developer provisioning may only require re-signing once a year.

如何理解 swift 既 ? 同 !

如何理解 swift 既 ? 同 !

假設有 Class 叫 Animal

Animal? 並不要好似網上d tutorial 話 一係有一係 nil 咁理解

不如你當佢係未知的禮物 type 咁理解 (inspired by wrapped / unwrapped)

Animal? 有兩個狀態 1: S<Type> 或者 2: nil

唔係 nil 就可以打開佢, 打開左先係以前我地認識既 var

呢個世界有 3 個方法去打開禮物包

  1. ! 強行打開

  2. if let abc = xyz { } 禮物打開咪做下面d logic

  3. abc?.function() 有咪行個 function 囉

as? as! 都類似

as! 有機會 nil -> runtime error

as? 就要用 if let 幫幫手

if let animalSelectedNode = selectedNode as? AnimalSpriteNode {


[ios] convert mpmediaitem to m4a

-(NSString*)convertToM4A : (MPMediaItem * ) mediaItem {
    NSURL *url = [mediaItem valueForProperty: MPMediaItemPropertyAssetURL];

    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL: url options:nil];

    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset

    exporter.outputFileType = @"";

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * myDocumentsDirectory = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

    /* Using date to be file name so no conflict
    [[NSDate date] timeIntervalSince1970];
    NSTimeInterval seconds = [[NSDate date] timeIntervalSince1970];
    NSString *intervalSeconds = [NSString stringWithFormat:@"%0.0f",seconds];*/

    NSString* mediaTitle = [mediaItem valueForProperty:MPMediaItemPropertyTitle];
    NSString* songTitle = [[NSString alloc]initWithFormat:@"%@",(mediaTitle.length>0 ? mediaTitle : @"Unknown")];

    NSString * fileName = [NSString stringWithFormat:@"%@.m4a", songTitle];

    NSString *exportFile = [myDocumentsDirectory stringByAppendingPathComponent:fileName];

    NSURL *exportURL = [NSURL fileURLWithPath:exportFile];
    exporter.outputURL = exportURL;

    // do the export
    // (completion handler block omitted)
    [exporter exportAsynchronouslyWithCompletionHandler:
         int exportStatus = exporter.status;

         switch (exportStatus)
             case AVAssetExportSessionStatusFailed:
                 NSError *exportError = exporter.error;
                 NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);
             case AVAssetExportSessionStatusCompleted:
                 NSLog (@"AVAssetExportSessionStatusCompleted");
                  NSData *data = [NSData dataWithContentsOfFile: [myDocumentsDirectory

                  NSLog(@"Data %@",data);
                  data = nil;
             case AVAssetExportSessionStatusUnknown:
                 NSLog (@"AVAssetExportSessionStatusUnknown"); break;
             case AVAssetExportSessionStatusExporting:
                 NSLog (@"AVAssetExportSessionStatusExporting"); break;
             case AVAssetExportSessionStatusCancelled:
                 NSLog (@"AVAssetExportSessionStatusCancelled"); break;
             case AVAssetExportSessionStatusWaiting:
                 NSLog (@"AVAssetExportSessionStatusWaiting"); break;
                 NSLog (@"didn't get export status"); break;
    return [exportURL absoluteString];

[ios aubio]ld: symbol(s) not found for architecture arm64

Undefined symbols for architecture arm64:
  "_vDSP_ctoz", referenced from:
      _aubio_fft_do_complex in aubio(fft.c.1.o)
  "_vDSP_fft_zrip", referenced from:
      _aubio_fft_do_complex in aubio(fft.c.1.o)
  "_vDSP_minv", referenced from:
      _fvec_min in aubio(mathutils.c.1.o)
  "_vDSP_create_fftsetup", referenced from:
      _new_aubio_fft in aubio(fft.c.1.o)
  "_vDSP_maxvi", referenced from:
      _fvec_max_elem in aubio(mathutils.c.1.o)
  "_vDSP_vsmul", referenced from:
      _aubio_fft_do_complex in aubio(fft.c.1.o)
  "_vDSP_maxv", referenced from:
      _fvec_max in aubio(mathutils.c.1.o)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Don’t cry.
Try to import Accelerate.framework which is default in frameworks of xcode.

music player in background ios

Solution 1. MPMusicPlayer ipodPlayer

it is actually calling the ipod player, which it is not related to the app anymore. Easy implement, 但有時 load 得多歌 會有d lag, 超建議開多個 tableView 做, 可以 store 住d mediaItemCollection, 因為呢個 framework 係唔會 交返d mediaItemCollection 你, 除非你用 hidden private API

Solution 2. AVPlayer with MPRemoteCommandCenter and MPNowPlayingInfoCenter

you can implement like this. Good Point is the music playing will also appear in the universal toolbar (the bottom one), and click one it, it will show yr app instead of ipod Music. Bad Point is no itunes cloud music can play, and many feature need to implement yrself, 連 previous 都好似無, shuffle 都有d 難做, 但用個d remoteCommand , 下面d 制都可以用, 同埋 用 nowplayinginfocenter 可以 改個 lock screen 個d song info. 無記錯呢個方法要改少少 plist, 有 background audio, 如果做完前者, 出 app無 聲, 試下

MPMusicPlayer ApplicationPlayer is a good choice 如果你想只播歌係你個 app 入面, 因為一出 app 就會 收聲

ref: (solution 1)

小米音樂 app (solution 2)

UIBarButtonItem title 入 nil 唔好入 @””

用 code 整 nav button … 如果無 title 就入 nil … 入 @”” … 佢會因為其他有 component 郁 而 會移動並出現在 strange position

UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithTitle:@""

UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithTitle:nil

property inheritance in ios

How to access backing ivars for inherited properties in Objective-C
I had a superclass that declared and synthesized a read only property, meant to be set in its subclasses. The code was something like this:

@interface A : NSObject
@property (nonatomic, readonly) NSUInteger prop;

@implementation A
@synthesize prop = _prop;

@interface B : A

@implementation B

  • (void)establishValueForProp
    _prop = 1; // PROBLEM !!!


The instance variable backing the property seemed to be invisible in the subclass. The error was pretty unclear when compiling an iOS app: “Use of undeclared identifier ‘_prop'”. To get around the error I did the following:

@interface A : NSObject {
NSUInteger _prop;
@property (nonatomic, readonly) NSUInteger prop;

That is, I explicitly declared the backing variable in the declaration of the superclass.

Interestingly, when I was preparing this blog post I compiled the code above as a “Command Line Tool” type of project, not an iOS app. The error was different, dare I say better, more telling of the root cause: “Instance variable ‘_prop’ is private”. So it’s a matter of the visibility of the ivar, so perhaps a better fix would be:

@interface A : NSObject {
NSUInteger _prop;
@property (nonatomic, readonly) NSUInteger prop;

Kind of interesting though that properties are synthesized by default as private ivars. Learned something new.
Posted by Bogdan Hapca at 12:09 PM
Email This
Share to Twitter
Share to Facebook
Share to Pinterest

Labels: iOS, Objective-C
1 comment:

Liviu Macsen said…
Thank your Bogdan for your solution. I found that you can also synthesize in subclass in order to solve this problem.

@implementation B

@synthesize prop = _prop;

  • (void)establishValueForProp
    _prop = 1; // Working !!!



debug YES becoz u only want to build in your testing device (or compile too long time and waste the other arch build)

release NO u should make sure all ios devices can run

set segue.destinationViewController property

method 1. typecast

APPDetailViewController myController = (APPDetailViewController)segue.destinationViewController;
myController.myString = string;

method 2. selector

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    if ([segue.destinationViewController respondsToSelector:@selector(setMyData:)]) {
         [segue.destinationViewController performSelector:@selector(setMyData:) 

in destination View Controller

@property (nonatomic, strong) MyData *myData;

Assertion failure in -[XXXView layoutSublayersOfLayer:]

2014-08-06 12:17:02.511 Jtab[6255:60b] *** Assertion failure in -[JTChordCollectionView layoutSublayersOfLayer:], /SourceCache/UIKit/UIKit-2935.138/UIView.m:8794 2014-08-06 12:17:02.512 Jtab[6255:60b] *** Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘Auto Layout still required after executing -layoutSubviews. JTChordCollectionView’s implementation of -layoutSubviews needs to call super.’

    [super layoutSubviews];

    [chordLabelView makeConstraints:^(MASConstraintMaker *make) {

solve by add [super layoutSubviews]; before add constraints ….


-(void)fitFontSize:(UILabel*)label {
CGFloat actualFontSize;
[label.text sizeWithFont:label.font
label.font = [label.font fontWithSize:actualFontSize];
label.adjustsFontSizeToFitWidth = NO;

usage: self.keyLabel = [self makeLabel:[UIFont fontWithName:@”AkzidenzGroteskBE-BoldCn” size:45.0f]];

    self.keyLabel.frame = CGRectMake(0, 0, self.cellWidth / 4.0, self.cellHeight);
    self.keyLabel.text = @"C";

    [self fitFontSize:self.keyLabel];
    [self.keyLabel sizeToFit];
    [self.keyLabel makeConstraints:^(MASConstraintMaker *make) {

Masonry in ios

constraints is funny

if u use Masonry or updateConstraints to a UIView, may no reaction till u drag one constraints to it…


  1. storyboard default has constraints already (if u dun drag any) it just the current frame be the constraints (if u tick autolayout which is usually ticked)
  2. when u drag the constraints, it override
  3. when u code using Masonry or constrains programming, it override

But sometimes it will say broken, becoz the constraints jammed… so… one solution:

it will ignore all the storyboard constraints, so u can use the coding one now.

auto size font size uilabel

- (void)drawPageLabel {
  self.pageLabel = [[UILabel alloc] init];

  [self addSubview: self.pageLabel];

  self.pageLabel.textColor = [UIColor blackColor];
  [self.pageLabel setAlpha:0.5];
  self.pageLabel.font = [self.pageLabel.font fontWithSize:140];
  [self.pageLabel setNumberOfLines:1];
  self.pageLabel.adjustsFontSizeToFitWidth = YES;
  self.pageLabel.minimumScaleFactor = 0.5f;

  // get a approiate font size using "1" char
  self.pageLabel.text = @"1";

  // make a frame for it to adjust it width for suitable fontSize
  CGFloat innerCircleWidth = self.radius * 0.2f * 2;
  self.pageLabel.frame = CGRectMake(0, 0, innerCircleWidth, innerCircleWidth); // maintain a square size

  // remeber the recommended font size
  CGFloat actualFontSize;
  [self.pageLabel.text sizeWithFont:self.pageLabel.font

  // use the recommended font size and dun adjust anymore
  [self.pageLabel setFont:[UIFont systemFontOfSize:actualFontSize]];
  [self.pageLabel sizeToFit];

  self.pageLabel.adjustsFontSizeToFitWidth = NO;

-(void)updatePageLabel:(int)currentNumber {
  self.pageLabel.text = [NSString stringWithFormat:@"%d", currentNumber];
  [self.pageLabel sizeToFit];
  self.pageLabel.frame = CGRectMake(self.pageLabel.superview.frame.size.width/2 - self.pageLabel.frame.size.width/2,
                                    self.pageLabel.superview.frame.size.height/2 - self.pageLabel.frame.size.height/2,

CGFloat actualFontSize;
[self.pageLabel.text sizeWithFont:self.pageLabel.font

this make my life … get the recommend font size after adjustsFontSizeToFitWidth
stupid sizeToFit only fit for the setted font size

kvo , key value observer script

in swipeView:

pair set:
– willChangeValueForKey:
– didChangeValueForKey:

or call this
- setValue:forKey:

[self.swipeView addObserver:self

self 個到有

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

[ios] filter music from ios by MPMediaQuery

MPMediaQuery *songQuery = [MPMediaQuery artistsQuery];
// OR
MPMediaQuery *songQuery = [MPMediaQuery songsQuery];

// local only
[songQuery addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:[NSNumber numberWithBool:NO] forProperty:MPMediaItemPropertyIsCloudItem]];

NSArray *songs = [songQuery items];

And u will retrieve a list … but music video is still here…
becoz music video is 2049 … ok u see

enum {
// audio
MPMediaTypeMusic = 1 << 0, MPMediaTypePodcast = 1 << 1, MPMediaTypeAudioBook = 1 << 2, MPMediaTypeAudioITunesU = 1 << 3, // available in iOS 5.0 MPMediaTypeAnyAudio = 0x00ff, // video (available in iOS 5.0) MPMediaTypeMovie = 1 << 8, MPMediaTypeTVShow = 1 << 9, MPMediaTypeVideoPodcast = 1 << 10, MPMediaTypeMusicVideo = 1 << 11, MPMediaTypeVideoITunesU = 1 << 12, MPMediaTypeAnyVideo = 0xff00, MPMediaTypeAny = ~0 }; typedef NSInteger MPMediaType; tht's it: MPMediaTypeMusic: 1 MPMediaTypePodcast: 2 MPMediaTypeAudioBook: 4 MPMediaTypeAudioITunesU: 8 (iOS 5) MPMediaTypeAnyAudio: 255 MPMediaTypeMovie: 256 MPMediaTypeTVShow: 512 MPMediaTypeVideoPodcast: 1024 MPMediaTypeMusicVideo: 2048 MPMediaTypeVideoITunesU: 4096 MPMediaTypeAnyVideo: 65280 2049 is MPMediaTypeMusicVideo + MPMediaTypeMusic MPMediaQuery *songQuery = [MPMediaQuery artistsQuery]; OR MPMediaQuery *songQuery = [MPMediaQuery songsQuery]; OR [songQuery addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:[NSNumber numberWithInteger:MPMediaTypeMusic] forProperty:MPMediaItemPropertyMediaType]]; even add comparisonType:MPMediaPredicateComparisonEqualTo 3 methods no work ... it want mediaType contain 1 and 2049 is still here method : filter it: NSArray *songs = [songQuery items]; NSMutableArray *finalSongs = [NSMutableArray array]; [songs enumerateObjectsUsingBlock:^(MPMediaItem *song, NSUInteger idx, BOOL *stop) { NSInteger mediaValue = [[song valueForProperty:MPMediaItemPropertyMediaType] integerValue]; if (mediaValue == 1) [finalSongs addObject:song]; }];

AFNetworking using manager to eat @”text/plain”

make AFHTTPRequestOperationManager can eat text/plain (or other content-type)
rmb re-init serializer for it…
the default one like JSON very much … but i m not doing JSON …

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@”text/plain”];

rmb add “file://” when using multipart form file
NSString *file = [[NSString alloc] initWithFormat: @”file://{file_address}];

import vamp into ios

put all library into a Vendors/VampPlugin folder
add -lstdc into build settings, other linker flags
edit the to “library” if needed
(dun add the simple host first)
comment the main a gXXx.c , since it crash the “main”
compile and goodbye

[ios] audio conversion using AVAssetExportSession / AVAssetWriter from AVFoundation

Target : ipod library -> aiff / wav / caf (which eat by libsndfile (already ported to ios))

first, i think AVAssetExportSession can solve my problem due to this link:

but it is for converted-to-mp3 only (or converted-to-m4a)

(Trick :

Some points you need notice:
when you init AVAssetExportSession object, the “presetName” argument must be “AVAssetExportPresetPassthrough”.
The “outputFileType” may be “”.

And rename to mp3)

why i know it is for mov or m4a

if u write :
NSLog(@”export.supportedFileTypes : %@”,export.supportedFileTypes);

u will get:
exporter.supportedFileTypes : (

but it is only telling u these type exporter can convert
in api:
Not all presets are compatible with all assets.

So after i run
NSLog(@”%@”, [AVAssetExportSession exportPresetsCompatibleWithAsset:songAsset]);
2014-05-27 18:29:35.792 Jtab[1723:60b] (

only m4a is available (and mp3 using mov one)
whatever your ipod library song is mp3, m4a, wav (i tried)
so it is fail

And note that using AVAssetExportSession, the output extension is concerned, if type != extension will error

So i go to other solution AVAssetWriter:

wav example:

wav example:

caf example:


Easy AAC compressed audio conversion on iOS

Easy AAC compressed audio conversion on iOS


But i think use AVAssetExportSession to m4a can solve the problem…,so TPAACAudioConverter is useless now

strong vs retain and weak vs assign and blah blah blah

After reading so many articles, SO posts and demo apps to check variable property attributes, I decided to put all the attributes information together:

atomic //default
strong=retain //default
assign //default
readwrite //default
Below is the detailed article link where you can find above mentioned all attributes, that will definitely help you. Many thanks to all the people who give best answers here!!

Variable property attributes or Modifiers in iOS

1.strong (iOS4 = retain )

it says “keep this in the heap until I don’t point to it anymore”
in other words ” I’am the owner, you cannot dealloc this before aim fine with that same as retain”
You use strong only if you need to retain the object.
By default all instance variables and local variables are strong pointers.
We generally use strong for UIViewControllers (UI item’s parents)
strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

@property (strong, nonatomic) ViewController *viewController;

@synthesize viewController;
2.weak –

it says “keep this as long as someone else points to it strongly”
the same thing as assign, no retain or release
A “weak” reference is a reference that you do not retain.
We generally use weak for IBOutlets (UIViewController’s Childs).This works because the child object only needs to exist as long as the parent object does.
a weak reference is a reference that does not protect the referenced object from collection by a garbage collector.
Weak is essentially assign, a unretained property. Except the when the object is deallocated the weak pointer is automatically set to nil
Example :

@property (weak, nonatomic) IBOutlet UIButton *myButton;

@synthesize myButton;
Strong & Weak Explanation:

Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying “Look! A dog!” As long as the dog is still on the leash, the little kids can still see the dog, and they’ll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).

3.retain = strong

it is retained, old value is released and it is assigned retain specifies the new value should be sent
retain on assignment and the old value sent -release
retain is the same as strong.
apple says if you write retain it will auto converted/work like strong only.
methods like “alloc” include an implicit “retain”

@property (nonatomic, retain) NSString *name;

@synthesize name;

assign is the default and simply performs a variable assignment
assign is a property attribute that tells the compiler how to synthesize the property’s setter implementation
I would use assign for C primitive properties and weak for weak references to Objective-C objects.

@property (nonatomic, assign) NSString *address;

@synthesize address;
share|improve this answer
edited Nov 14 ’13 at 8:25

cannot get position, or cell reuse animation cannot control

if u r doing AVAudioPlayer, and u grep currentTime, if u wanna has a more accurate time, it cannot do it … since it is quite discrete (for compress song like mp3) … so

CACurrentMediaTime() may help u

beginTime = CACurrentMediaTime()

… some animation …

animateTime = CACurrentMediaTime() – beginTime

so i have some value can calculate the view if the animation wanna pause in the middle

(too complicated animation recommend use CAKeyFrameAnimation)

[ios] declare const

1. private

NSString *const SelectionSort = @”SelectionSort”;

2. public

extern NSString *const SelectionSort;
and in myfile.m define them

NSString *const SelectionSort = @”SelectionSort”;

It works, but only if you need a non global constant. Static constant is not visible outside the file. Otherwise use the 1st option.


The #define is a pre-processor macro. That means that it basically goes through your code and replace your macro with what you’ve defined.

If you use a const, it’s going to be a pointer to the string in memory. It’s way more efficient than having the same string being allocated wherever/whenever it is used.

To do that, you’ll need both .h and .m files. Your .h file will look something like:

extern NSString * const YOUR_STRING;
And your .m file:

NSString * const YOUR_STRING = @”your string”;

no need Class.THIS_IS_A_CONST , just THIS_IS_A_CONST then ok


會出現warning:(Sending ‘const NSString *__strong’ to parameter of type ‘NSString *’ discards qualifiers)
extern NSString * SelectionSort;
const NSString *InsertionSort = @”SelectionSort”;

extern NSString *const SelectionSort;
NSString *const SelectionSort = @”SelectionSort”;

UICollectionView 的心路歷程

project 是寫一個 guitar chord + music player
data 只有 那些 chord, 我的 project 就是要 用 cell 一格格的跟住音樂 著燈

1. using UICollectionView
problem 1: offset
因為我用了 endTime – startTime, 原來會累積 一些 error ,導致後面不準

problem 2: UICollectionView reloaditemsAtIndexPath 有 animation 在閃
求其 set 了 就繼續做
[UIView setAnimationsEnabled:NO];

到第一個 deadline : 發現這兩問題

首先要解決閃的問題,因為 setAnimationsEnabled:NO 會令到 needle (音樂器的秒數指標)

solution 1 : 用了 PSTCollectionView ,改 src code, 熄了那 .3 的 animation
所以轉了第二個 function

用 reloadData , 其實是整幅 cells reload
壞處是不能有 animation 在其中,不斷 call 的話,scroll 也不能
visibleCells 也有不準的情況 (其實放在 reload 前 就會o岩了)

offset 問題,本想用 ticker 可處理
每 0.01 秒去 發 notification 和 cells 對話
cells 轉自己的 isCurrentChord = YES 同埋
call delegate (viewController) 話邊粒係 current
本應很好,但 0.01 秒去 call 一個 reload function
call reloadData 還好,call reloaditemsAtIndexPath 簡直炒晒
因為 refresh 得太密, scroll 要自己設計,click 亦不能,此路不通

solution 3 : 返回基本步,用 UICollectionView ,仍覺得閃可以解決,使用了
[UIView animateWithDuration:0 animations:^{
[collectionView performBatchUpdates:^{
[collectionView reloadItemsAtIndexPaths:indexPaths];
} completion:nil];

needle 仍舊不能動

好友提議下,將 endTime – startTime 改成 currentCell.startTime – musicPlayer.currentTime 做 timer interval
currentIndex++ after one timer trigger

offset 問題解決了,誤差不會再 stack 上去, 就算有誤差,都係本身一個 cell 的極少誤差

reloadItemsAtIndexPaths 不能用,唯有用 relaodData
注意 reloadData 係 async 的
亦 rmb use layoutIfNeeded 去 trigger update
但因為無用 ticker, 小心處理動畫問題,用起上來蠻方便的

Solve WebView problem


add this back 有discuss

try this, turn off the alpha channel (no use)

more ref, and have many hints !

change to translateX (try)

or read this

add this
-webkit-overflow-scrolling: touch;

change RenderPriority and CACHE SETTING (try)!topic/android-developers/4YATUvb-t68

try large heap true (try)

change all png to jpg
(no transparency channel in yr app)

smooth transition trial

1. try webkit back face visibility hide
2. try the slide animation time is linear ie deltaX * 10ms, but not diff distance but same time
3. try window.location.href = “#body” to do a fast auchor

good luck

blackberry debug token

About Configuring your application

About tablet xml