本文目录一览:
什么时候用懒加载
1.懒加载基本
懒加载——也称为延迟加载,即在需要的时候才加载(效率低,占用内存小)。所谓懒加载,写的是其get方法.
注意:如果是懒加载的话则一定要注意先判断是否已经有了,如果没有那么再去进行实例化
2.使用懒加载的好处:
(1)不必将创建对象的代码全部写在viewDidLoad方法中,代码的可读性更强
(2)每个控件的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合
3.代码示例
1 //
2 // YYViewController.m
3 // 03-图片浏览器初步
4 //
5 // Created by apple on 14-5-21.
6 // Copyright (c) 2014年 itcase. All rights reserved.
7 //
8
9 #import “YYViewController.h”
10
11 #define POTOIMGW 200
12 #define POTOIMGH 300
13 #define POTOIMGX 60
14 #define POTOIMGY 50
15
16 @interface YYViewController ()
17
18 @property(nonatomic,strong)UILabel *firstlab;
19 @property(nonatomic,strong)UILabel *lastlab;
20 @property(nonatomic,strong)UIImageView *icon;
21 @property(nonatomic,strong)UIButton *leftbtn;
22 @property(nonatomic,strong)UIButton *rightbtn;
23 @property(nonatomic,strong)NSArray *array;
24 @property(nonatomic ,assign)int i;
25 -(void)change;
26 @end
27
28
29
30 @implementation YYViewController
31
32 – (void)viewDidLoad
33 {
34 [super viewDidLoad];
35 [self change];
36 }
37
38 -(void)change
39 {
40 [self.firstlab setText:[NSString stringWithFormat:@”%d/5″,self.i+1]];
41 //先get再set
42
43 self.icon.image=[UIImage imageNamed:self.array[self.i][@”name”]];
44 self.lastlab.text=self.array[self.i][@”desc”];
45
46 self.leftbtn.enabled=(self.i!=0);
47 self.rightbtn.enabled=(self.i!=4);
48 }
49
50 //延迟加载
51 /**1.图片的序号标签*/
52 -(UILabel *)firstlab
53 {
54 //判断是否已经有了,若没有,则进行实例化
55 if (!_firstlab) {
56 _firstlab=[[UILabel alloc]initWithFrame:CGRectMake(20, 10, 300, 30)];
57 [_firstlab setTextAlignment:NSTextAlignmentCenter];
58 [self.view addSubview:_firstlab];
59 }
60 return _firstlab;
61 }
62
63 /**2.图片控件的延迟加载*/
64 -(UIImageView *)icon
65 {
66 //判断是否已经有了,若没有,则进行实例化
67 if (!_icon) {
68 _icon=[[UIImageView alloc]initWithFrame:CGRectMake(POTOIMGX, POTOIMGY, POTOIMGW, POTOIMGH)];
69 UIImage *image=[UIImage imageNamed:@”biaoqingdi”];
70 _icon.image=image;
71 [self.view addSubview:_icon];
72 }
73 return _icon;
74 }
75
76 /**3.描述控件的延迟加载*/
77 -(UILabel *)lastlab
78 {
79 //判断是否已经有了,若没有,则进行实例化
80 if (!_lastlab) {
81 _lastlab=[[UILabel alloc]initWithFrame:CGRectMake(20, 400, 300, 30)];
82 [_lastlab setTextAlignment:NSTextAlignmentCenter];
83 [self.view addSubview:_lastlab];
84 }
85 return _lastlab;
86 }
87
88 /**4.左键按钮的延迟加载*/
89 -(UIButton *)leftbtn
90 {
91 //判断是否已经有了,若没有,则进行实例化
92 if (!_leftbtn) {
93 _leftbtn=[UIButton buttonWithType:UIButtonTypeCustom];
94 _leftbtn.frame=CGRectMake(0, self.view.center.y, 40, 40);
95 [_leftbtn setBackgroundImage:[UIImage imageNamed:@”left_normal”] forState:UIControlStateNormal];
96 [_leftbtn setBackgroundImage:[UIImage imageNamed:@”left_highlighted”] forState:UIControlStateHighlighted];
97 [self.view addSubview:_leftbtn];
98 [_leftbtn addTarget:self action:@selector(leftclick:) forControlEvents:UIControlEventTouchUpInside];
99 }
100 return _leftbtn;
101
102 }
103
104 /**5.右键按钮的延迟加载*/
105 -(UIButton *)rightbtn
106 {
107 if (!_rightbtn) {
108 _rightbtn=[UIButton buttonWithType:UIButtonTypeCustom];
109 _rightbtn.frame=CGRectMake(POTOIMGX+POTOIMGW+10, self.view.center.y, 40, 40);
110 [_rightbtn setBackgroundImage:[UIImage imageNamed:@”right_normal”] forState:UIControlStateNormal];
111 [_rightbtn setBackgroundImage:[UIImage imageNamed:@”right_highlighted”] forState:UIControlStateHighlighted];
112 [self.view addSubview:_rightbtn];
113 [_rightbtn addTarget:self action:@selector(rightclick:) forControlEvents:UIControlEventTouchUpInside];
114 }
115 return _rightbtn;
116 }
117
118 //array的get方法
119 -(NSArray *)array
120 {
121 if (_array==nil) {
122 NSString *path=[[NSBundle mainBundle] pathForResource:@”data” ofType:@”plist”];
123 _array=[[NSArray alloc]initWithContentsOfFile:path];
124 }
125 return _array;
126 }
127
128 -(void)rightclick:(UIButton *)btn
129 {
130 self.i++;
131 [self change];
132 }
133
134 -(void)leftclick:(UIButton *)btn
135 {
136 self.i–;
137 [self change];
138 }
139
140 @end
python作业求帮助
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File name: parabolic
# Project name: parabolic_equation
“””
.. moduleauthor::
.. Module.. name parabolic of procjet parabolic_equation
“””
from sympy import *
import matplotlib.pyplot as plt
import numpy as np
def _filterComplex(inputvalue, description=’inputvalue’):
try:
str(inputvalue).index(‘I’)
except ValueError:
return False
else:
return True
def _checkBool(inputvalue, description=’inputvalue’):
“””
:param inputvalue:
:param description:
:return:
“””
if not isinstance(inputvalue, bool):
raise TypeError(
‘The {0} must be boolean. Given: {1!r}’.format(description, inputvalue))
def _checkNumerical(inputvalue, description=’inputvalue’):
“””
:param inputvalue:
:param description:
:return:
“””
try:
inputvalue + 1
except TypeError:
raise TypeError(
‘The {0} must be numerical. Given: {1!r}’.format(description, inputvalue))
def _drawTowPara(expr_1, expr_2, inputmin, inputmax ,step=0.1):
“””
:param expr_1:
:param expr_2:
:param inputmin:
:param inputmax:
:param step:
:param expr_1_evalwithY:
:param expr_2_evalwithY:
:return:
“””
_checkNumerical(inputmin, ‘xmin’)
_checkNumerical(inputmax, ‘xmax’)
_checkNumerical(step, ‘step’)
y1List = []
x1List = []
y2List = []
x2List = []
if expr_1.vertical is True:
x1List = np.arange(inputmin, inputmax, step)
for x in x1List:
y1List.append(expr_1.evaluates_Y(x))
else:
y1List = np.arange(inputmin, inputmax, step)
for y in y1List:
x1List.append(expr_1.evaluates_X(y))
if expr_2.vertical is True:
x2List = np.arange(inputmin, inputmax, step)
for x in x2List:
y2List.append(expr_2.evaluates_Y(x))
else:
y2List = np.arange(inputmin, inputmax, step)
for y in y2List:
x2List.append(expr_2.evaluates_X(y))
plt.plot(x1List, y1List, ‘+’)
plt.plot(x2List, y2List, ‘-‘)
plt.show()
def _solveCrossing(expr_1, expr_2):
“””
:param expr_1:
:param expr_2:
:return:
“””
x = Symbol(‘x’)
y = Symbol(‘y’)
print “Given the first expression: {0!r}”.format(expr_1.expr)
print “Given the first expression: {0!r}”.format(expr_2.expr)
ResultList = solve([expr_1.expr, expr_2.expr], [x, y])
Complex = False
ResultListTrue = []
for i in range(0, (len(ResultList)),1):
if _filterComplex(ResultList[i][0], ‘x’) or _filterComplex(ResultList[i][1], ‘y’):
Complex = True
else:
ResultListTrue.append(ResultList[i])
if len(ResultListTrue) == 0 and Complex:
print “Two hyperbolic do not intersect, and there is imaginary value.”
elif len(ResultListTrue) == 1:
print “Two hyperbolic tangent.:”
print ResultListTrue
else:
print “Two hyperbolic intersection, and Points are:”
for iterm in ResultListTrue:
print iterm
class Parabolic():
“””
“””
def __init__(self, a, b, c, vertical=True):
“””
:return:
“””
_checkNumerical(a, ‘a’)
_checkNumerical(b, ‘b’)
_checkNumerical(c, ‘c’)
_checkBool(vertical, ‘vertical’)
self.a = a
self.b = b
self.c = c
self.vertical = vertical
self.y = Symbol(‘y’)
self.x = Symbol(‘x’)
self.xarray = []
self.yarray = []
if vertical is True:
self.expr = (self.x**2)*self.a + self.x*self.b + self.c
else:
self.expr = (self.y**2)*self.a + self.y*self.b + self.c
def __repr__(self):
“””
:return:
“””
if self.vertical is True:
return “The Equation look like: {0!r}”.format(self.expr)
else:
return “The Equation look like: {0!r}”.format(self.expr)
def evaluates_X(self, inputvalue):
“””
:param inputvalue:
:return:
“””
_checkNumerical(inputvalue, ‘y’)
return self.expr.subs(self.y, inputvalue)
def evaluates_Y(self, inputvalue):
“””
:param inputvalue:
:return:
“””
_checkNumerical(inputvalue, ‘x’)
return self.expr.subs(self.x, inputvalue)
def getArrays(self, inputmin, inputmax, step=1):
“””
:param inputmin:
:param inputmax:
:param step:
:return:
“””
_checkNumerical(inputmin, ‘xmin’)
_checkNumerical(inputmax, ‘xmax’)
_checkNumerical(step, ‘step’)
if self.vertical is True:
for x in range(inputmin, inputmax, step):
self.xarray.append(x)
self.yarray.append(self.evaluates_Y(x))
else:
for y in range(inputmin, inputmax, step):
self.yarray.append(y)
self.xarray.append(self.evaluates_X(y))
def drawPara(self, inputmin, inputmax, step=1):
“””
:param inputmin:
:param inputmax:
:param step:
:return:
“””
_checkNumerical(inputmin, ‘xmin’)
_checkNumerical(inputmax, ‘xmax’)
_checkNumerical(step, ‘step’)
yList = []
xList = []
if self.vertical is True:
xList = np.arange(inputmin, inputmax, step)
for x in xList:
yList.append(self.evaluates_Y(x))
else:
yList = np.arange(inputmin, inputmax, step)
for y in yList:
xList.append(self.evaluates_X(y))
plt.plot(xList, yList, ‘+’)
plt.show()
if __name__ == ‘__main__’:
pa1 = Parabolic(-5,3,6)
pa2 = Parabolic(-5,2,5, False)
print pa1
print pa2
_solveCrossing(pa1, pa2)
_drawTowPara(pa1, pa2, -10, 10, 0.1)
# 这就是你想要的,代码解决了你的大部分问题,可以求两条双曲线交点,或者直线与双曲线交#点,或者两直线交点. 不过定义双曲线时候使用的是一般式.也也尽可能做了测试,如果有#问题的话,追问吧
iOS 高德地图轨迹回放的 思路, 及方法
// 开始,公司要求制作一段跑步轨迹 在地图上的 动画回放, 传入一段经纬度,
开始一想,这不是很简单吗, 高德地图有可以把经纬度转换成坐标点的方法
/**
* @brief 将经纬度转换为指定view坐标系的坐标
* @param coordinate 经纬度
* @param view 指定的view
* @return 基于指定view坐标系的坐标
*/
– (CGPoint)convertCoordinate:(CLLocationCoordinate2D)coordinate toPointToView:(UIView *)view;
// 我把经纬度转换成坐标点, 然后构建 path
/* 构建path, 调用着负责释放内存. */
– (CGMutablePathRef)pathForPoints:(CGPoint *)points count:(NSUInteger)count
{
if (points == NULL || count = 1)
{
return NULL;
}
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddLines(path, NULL, points, count);
return path;
}
// 在然后直接用 path ,初始化一个 CAShapeLayer ,做成动画不就成了 吗, 在它跑完之后直接删除, 再用 高德地图的折线替换,
// 这种方法也可以, 但是后来需求改了, 要求地图旋转,并且地图中心点一直在跑动的点上,
这样,我以屏幕坐标构建的 path 一旦地图旋转, 就全乱了,
// 后来我又想到一个办法, 我从地图手机上定位画线得到的灵感, 我把经纬度点两个两个连成一个个短的折线,放到一个数组里面 ,然后定义了一个 index 属性, 再用一个定时器不停的循环, 在定时器的方法中,用
[self.mapView addOverlay:self.mapOverlayArr[self.index] level:MAOverlayLevelAboveRoads];
不停加载线路在地图上, 同时把地图的中心点, 定位在 经纬度数组取到的最新的经纬度上
CLLocation * location = self.locationArray[self.index];
[self.mapView setCenterCoordinate:location.coordinate animated:NO];
,这样就能保证地图中心一直在跑动的点上, 而且定时器 方法 加载线路够快的话, 就能产生动画效果,
然而, 又出现了问题, 定时器不停的运行
mapView 不停的加载 addOverlay ,使得屏幕非常卡, 经纬度少的话还看不出来, 一旦经纬度多了, 卡的不要不要的, 完全受不了, 而且手机非常烫, 电池都快烧坏了,, 所以这种方法不可行, 至少不完善
// 后来我研究高德地图的画线方法, 发现一个 方法
/**
* @brief 重新设置折线坐标点. since 5.0.0
* @param coords 指定的经纬度坐标点数组, C数组,内部会做copy,调用者负责内存管理
* @param count 坐标点的个数
* @return 是否设置成功
*/
– (BOOL)setPolylineWithCoordinates:(CLLocationCoordinate2D *)coords count:(NSInteger)count;
// 这个方法只用一条折线, 但是可以不停的改变这条折线的位置,
终于利用这个方法 不卡了, 画线的过程中 FPS 60 左右, 完美
// 因为文件太大就 不上传了
Python数据结构之Array用法实例
Python数据结构之Array用法实例
这篇文章主要介绍了Python数据结构之Array用法实例,较为详细的讲述了Array的常见用法,具有很好的参考借鉴价值,需要的朋友可以参考下
import ctypes
class Array:
def __init__(self, size):
assert size 0, “Array size must be 0 “
self._size = size
pyArrayType = ctypes.py_object * size
self._elements = pyArrayType()
self.clear(None)
def clear(self, value):
for index in range(len(self)):
self._elements[index] = value
def __len__(self):
return self._size
def __getitem__(self, index):
assert index = 0 and index len(self), “index must =0 and = size”
return self._elements[index]
def __setitem__(self, index, value):
assert index = 0 and index len(self), “index must =0 and = size”
self._elements[index] = value
def __iter__(self):
return _ArrayIterator(self._elements)
class _ArrayIterator:
def __init__(self, theArray):
self._arrayRef = theArray
self._curNdr = 0
def __next__(self):
if self._curNdr len(theArray):
entry = self._arrayRef[self._curNdr]
sllf._curNdr += 1
return entry
else:
raise StopIteration
def __iter__(self):
return self
class Array2D :
def __init__(self, numRows, numCols):
self._theRows = Array(numCols)
for i in range(numCols):
self._theRows[i] = Array(numCols)
def numRows(self):
return len(self._theRows)
def numCols(self):
return len(self._theRows[0])
def clear(self, value):
for row in range(self.numRows):
self._theRows[row].clear(value)
def __getitem__(self, ndxTuple):
assert len(ndxTuple) == 2, “the tuple must 2”
row = ndxTuple[0]
col = ndxTuple[1]
assert row=0 and row len(self.numRows())
and col=0 and collen(self.numCols),
“array subscrpt out of range”
theArray = self._theRows[row]
return theArray[col]
def __setitem__(self, ndxTuple, value):
assert len(ndxTuple)==2, “the tuple must 2”
row = ndxTuple[0]
col = ndxTuple[1]
assert row = 0 and row len(self.numRows)
and col = 0 and col len(self.numCols),
“row and col is invalidate”
theArray = self._theRows[row];
theArray[col] = value
希望本文所述对大家的Python程序设计有所帮助。
iOS 判断数组为空
服务器返回有这个数组 但是这个数组里面是空的话
if(self.array.count == 0){}判断里面成员个数,个数是0 就是空了
Python多线程
那是当然。你这样写就可以了
self.p[:]=array
这样写法的含义就是指针不变。只换内容。这样就可以同步了。
你的写法是,新建一个数组,再把指针缎带self.p,如果其它的线程就会出问题。
另外你的p应该放在__init__之前。引用时使用T.p来引用,这样更合理一些。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/244391.html